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.
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?
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With