检测 JComboBox 编辑
我有一个 JComboBox,每秒一次,我想从数据库中检索一组字符串,并将这些字符串设置为 JComboBox 的内容,并将其中一个作为当前选定的值。但我还希望用户能够编辑 JComboBox 并向数据库添加值并将其设置为当前值。
我希望能够检测何时将字符输入 JComboBox,因此我可以重置倒计时,只要它不为零,就可以防止更新 JComboBox。我的第一反应是使用 KeyListener,但是组合框的 Java 教程是这样说的,
虽然 JComboBox 继承了注册监听器的方法 低级事件——例如焦点、按键和鼠标事件——我们 建议您不要侦听组合框上的低级事件。
他们接着说,触发的事件可能会根据外观和感觉而改变。
I have a JComboBox, once every second I want to retreive a set of strings from a database and set those strings to the contents of the JComboBox, and one of them as the currently selected value. But I also want the user to be able to edit the JComboBox and add a value to the database and set it as the current value.
I want to the be able to detect when characters are entered into the JComboBox, so I can reset a count down which prevents updating the JComboBox as long as it's not zero. My first instinct was to use a KeyListener but the Java tutorial on combo boxes says this,
Although JComboBox inherits methods to register listeners for
low-level events — focus, key, and mouse events, for example — we
recommend that you don't listen for low-level events on a combo box.
And they go on to say that the events fired may change depending on the look and feel.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这有点冒险,但它应该可以侦听编辑器组件(JTextField)上的文档更新。
对于从 JComboBox 中键入/删除的每个字符,都应该调用这些 *Update(DocumentEvent documentEvent) 方法。
This is a little dicey, but it should work to listen to the Document updates on the Editor component (A JTextField).
Those *Update(DocumentEvent documentEvent) methods should get called for every character typed/deleted from the JComboBox.
我想补充一点,changedUpdate 方法不会触发纯文本文档的通知。如果您使用纯文本文本组件,则必须使用 insertUpdate 和/或 removeUpdate。
如果用户正在编辑组合框,我最近不得不使用文档侦听器作为禁用/启用按钮的方法。我做了这样的事情并且工作得很好:
然后,我将此侦听器添加到组合框中,如下所示:
这之所以有效,是因为与组合框关联的文档是纯文本。当我使用changedUpdate时它没有。
I would like to add that the changedUpdate method will not fire a notification for plain text documents. If you are using a plain text text component, you must use insertUpdate and/or removeUpdate.
I recently had to use a document listener as a way of disabling/enabling a button if the user was editing the combo box. I did something like this and worked very well:
Then, I added this listener to the combo box like this:
This works because the document associated with the combo box is plain text. When I used changedUpdate it did not.