检测JComboBox编辑 [英] Detecting JComboBox editing

查看:42
本文介绍了检测JComboBox编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JComboBox,我想每秒一次检索数据库中的一组字符串并将这些字符串设置为JComboBox的内容,并将其中一个设置为当前选定的值.但我也希望用户能够编辑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.

我希望能够检测到何时在JComboBox中输入了字符,因此我可以重置倒数,只要它不为零,就可以防止更新JComboBox.我的第一个直觉是使用KeyListener,但是组合框上的Java教程对此做了说明,

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,

尽管JComboBox继承了用于注册侦听器的方法 低级事件-例如焦点,键和鼠标事件-我们 建议您不要在组合框上监听低级事件.

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.

推荐答案

这有点麻烦,但是它应该可以在Editor组件(一个JTextField)上侦听Document更新.

This is a little dicey, but it should work to listen to the Document updates on the Editor component (A JTextField).

    JComboBox cb = new JComboBox();
    Component editor = cb.getEditor().getEditorComponent();
    if (editor instanceof JTextField) {
        ((JTextField) editor).getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent documentEvent) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void removeUpdate(DocumentEvent documentEvent) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void changedUpdate(DocumentEvent documentEvent) {
                //To change body of implemented methods use File | Settings | File Templates.
            }
        });                                      
    }

对于从JComboBox键入/删除的每个字符,应调用* Update(DocumentEvent documentEvent)方法.

Those *Update(DocumentEvent documentEvent) methods should get called for every character typed/deleted from the JComboBox.

这篇关于检测JComboBox编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆