我有一个可编辑的JComboBox
。我只需要按照情况发射事件
在以下代码event fires while user typing in the editor as well
中,如何在用户输入时避免事件触发?
comboForward.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
new Thread() {
@Override
public void run() {
// code after the event.
}
}.start();
}
}
});
答案 0 :(得分:0)
我认为这适合你。试试吧。
JFrame frame = new JFrame("Welcome!!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox cmb = new JComboBox();
cmb.setEditable(true);
cmb.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent event) {
if (event.getKeyChar() == KeyEvent.VK_ENTER) {
if (((JTextComponent) ((JComboBox) ((Component) event
.getSource()).getParent()).getEditor()
.getEditorComponent()).getText().isEmpty())
System.out.println("please dont make me blank");
}
}
});
frame.add(cmb);
frame.setLocationRelativeTo(null);
frame.setSize(300, 50);
frame.setVisible(true);
请参阅此处:https://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html