`
aerchi
  • 浏览: 424627 次
  • 性别: Icon_minigender_1
  • 来自: 昆明
文章分类
社区版块
存档分类
最新评论

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

 
阅读更多
在输入数据较多的的窗体中,经常需要进行数据验证,即只有在某个数据输入合法的情况下才能进行其它操作,本文介绍了可编辑状态的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
import java.awt.Component;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MyJComboBox extends JFrame {
private static final long serialVersionUID = 1L;
private final String[] ITEMS = new String[] { "ITEM1", "ITEM2" };
private JComboBox comBox= new JComboBox(ITEMS);
private JButton btn=new JButton("提交");
private JTextField inputTxt=new JTextField(15);
public MyJComboBox() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("JComboBox测试");
//返回组合框编辑器的树层次结构中的组件
Component editorComponent = comBox.getEditor().getEditorComponent();
editorComponent.addKeyListener(new KeyAdapter() {
public void 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=new JPanel();
btnPanel.add(btn);
btnPanel.add(inputTxt);
this.add(btnPanel,"South");
this.pack();
}
public static void main(String[] args) {
MyJComboBox main = new MyJComboBox();
main.setVisible(true);
}
}
重要的API介绍:

1.getEditor

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

返回:

显示所选项的 ComboBoxEditor。

2.getEditorComponent

ComponentgetEditorComponent()

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

3.pack

public voidpack()调整此窗口的大小,以适合其子组件的首选大小和布局。如果该窗口和/或其所有者还不可显示,则在计算首选大小之前都将变得可显示。在计算首选大小之后,将会验证该窗口。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics