Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java swing combo box only calling listener once

Tags:

java

swing

Very new to Java and Swing, and I have been playing with a swing gui application. It generated some code for my combo box:

comboBox.addActionListener(EventHandler.create(ActionListener.class, TestController, "changeSomething"));

and i also have this:

import javax.swing.JComboBox;
import javax.swing.JOptionPane;

public class StudyPlanController {
    private JComboBox factors;

    public void changeSomething() {
        JOptionPane.showMessageDialog(null, "change!");
    }
}

I have 2 questions.

  1. When I change the selected item in the combo box i get the message "change!" only the first time it is changed. Why is this?

  2. When googling for a solution, all the code for setting up the listener was different to the code generated for me. e.g

    box.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent e){ System.out.println(e.getItem() + " " + e.getStateChange() ); } });

Is the way i'm createing the listener correct? why are there two ways to do this?

Thanks

like image 409
pingu Avatar asked Mar 04 '26 02:03

pingu


2 Answers

For JComboBox is better implements ItemListener, but this Listener is always called twice SELECTED and DESELECTED, you can check that if event is SELECTED/DESELECTED

   myComboBox.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                //some stuff
            }
        }
    });

You can use ActionListener, but I suggest to use that for changing itself own JComboBox's properties or methods, not to ouside from JComboBox, to ouside somewhere to the GUI

You can use EventHandler, but better would be start to leaning basic stuff before

like image 83
mKorbel Avatar answered Mar 05 '26 14:03

mKorbel


First an answer about EventHandler. Normally event handling is done as @mKorbel says. For many event listeners classes there are specific methods getting invoked on an event. This can lead to many anonymous inner classes. Therefore EventHandler was introduced. It is more efficient using reflection, and creates less objects. See http://docs.oracle.com/javase/7/docs/api/java/beans/EventHandler.html

Secondly, why it went wrong: I would expect:

comboBox.addItemListener(ItemListener.class, textController, "doSomething");

As @mKorbel said, because of the SELECTED test, it is better to not using EventHandler here.

like image 33
Joop Eggen Avatar answered Mar 05 '26 16:03

Joop Eggen