如何在JcomboBox中输入或更改所选项目后才触发事件

时间:2015-11-24 10:43:19

标签: java jcombobox

我有一个可编辑的JComboBox。我只需要按照情况发射事件

  1. 用户在键入时按Enter键(这可以实现添加键事件监听器)或
  2. 用户从列表中选择项目
  3. 在以下代码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();
                }
            }
        });
    

1 个答案:

答案 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