简体   繁体   中英

Java item event mouse click

I have to handle an event in a combobox when the user click the item (not when the combobox change the state).

I have four combobox: (1Combo: Parent category) (2 Combo: The sons of the category 1) (3 Combo: the sons of the category 2) (4 combo: the sons of the category 3)

Each one calls the list to add the items for the other one (the sons of the category choosed).

But my problem is that I have an itemstatechange event and I want to know if the item has been clicked NOT if the combo changes state.

public void itemStateChanged(ItemEvent e) {
    if (e.getSource()==jComboBoxCategorias1) {
        handleEventCombo1();
    }
    if (e.getSource()==jComboBoxCategorias2) {
       handleEventCombo2();
    } 
    if (e.getSource()==jComboBoxCategorias3) {
        handleEventCombo3();
    }
    if (e.getSource()==jComboBoxCategorias4) {
        handleEventCombo4();
    }

}

You can add a mouse listener to the combobox and implement the mouseClicked method.

comboBox.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println(comboBox.getSelectedItem());
        }
    });

Don't forget that comboBox is actually a container. So if you really want to have all the mouse events you should add the listener to all the components it contains.

public void addMouseListener(final MouseListener mouseListener) {
    this.comboBox.addMouseListener(mouseListener);

    final Component[] components = this.comboBox.getComponents();
    for(final Component component : components) {
      component.addMouseListener(mouseListener);
    }

    this.comboBox.getEditor().getEditorComponent().addMouseListener(mouseListener);
  }

Please visit swing mouse listeners being intercepted by child components for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM