监听可编辑JComboBox内容改变实现验证

来源:互联网 发布:小乔丹数据 编辑:程序博客网 时间:2024/06/06 04:01
在输入数据较多的的窗体中,经常需要进行数据验证,即只有在某个数据输入合法的情况下才能进行其它操作,本文介绍了可编辑状态的JComBox控件监听器内容改变的方法,如果JComboBox输入的数据不合法,则无法进行提交操作。程序实现的效果如下:

JComboBox内容不为空:
JComboBox内容为空:
Java代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
importjava.awt.Component;
importjava.awt.event.KeyAdapter;
importjava.awt.event.KeyEvent;
 
importjavax.swing.JButton;
importjavax.swing.JComboBox;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
 
publicclass MyJComboBox extendsJFrame {
    privatestatic final long serialVersionUID = 1L;
     
    privatefinal String[] ITEMS = newString[] { "ITEM1","ITEM2"};  
    privateJComboBox comBox= newJComboBox(ITEMS);
    privateJButton btn=newJButton("提交");
    privateJTextField inputTxt=newJTextField(15);
     
    publicMyJComboBox() { 
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("JComboBox测试");
        //返回组合框编辑器的树层次结构中的组件
        Component editorComponent = comBox.getEditor().getEditorComponent();
        editorComponent.addKeyListener(newKeyAdapter() {
            publicvoid keyReleased(KeyEvent evt) {
                String strItem = comBox.getEditor().getItem().toString();
                if(strItem.isEmpty())
                    btn.setEnabled(false);
                else
                    btn.setEnabled(true);
                inputTxt.setText(strItem);
            }
        });
        comBox.setEditable(true);
        this.add(comBox,"Center");     
        JPanel btnPanel=newJPanel();
        btnPanel.add(btn);
        btnPanel.add(inputTxt);
        this.add(btnPanel,"South");
        this.pack();
    }
 
    publicstatic void main(String[] args) {
        MyJComboBox main = newMyJComboBox();      
        main.setVisible(true);
    }
}
重要的API介绍:

1.getEditor

public ComboBoxEditor getEditor()返回用于绘制和编辑 JComboBox 字段中所选项的编辑器。

返回:

显示所选项的 ComboBoxEditor。

2.getEditorComponent

Component getEditorComponent()

返回应该添加到此编辑器的树层次结构中的组件。

3.pack

public void pack()调整此窗口的大小,以适合其子组件的首选大小和布局。如果该窗口和/或其所有者还不可显示,则在计算首选大小之前都将变得可显示。在计算首选大小之后,将会验证该窗口。
 
原创粉丝点击