我有一个可编辑的JComboBox
。我只需要在以下情况下触发事件
在下面的代码中,用户在编辑器中键入时事件也会触发
,如何避免用户键入时事件触发?
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();
}
}
});
我觉得这个适合你。试试吧。
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