Adding ActionListener to JComboBox without items not working
Question
Below is the source code for UseTest.java
. Why doesn't it work?
import javax.swing.* ;
import java.awt.* ;
import java.awt.event.* ;
class Test implements ActionListener{
JFrame f ;
JPanel p ;
JComboBox cb ;
JLabel l ;
Test(){
f = new JFrame("Test") ;
f.setSize(200, 200) ;
p = new JPanel() ;
p.setLayout(new GridLayout(2, 1)) ;
cb = new JComboBox() ;
cb.addActionListener(this) ;
for(int i = 1 ; i <= 20 ; i++)
cb.addItem(i + "") ;
//cb.addActionListener(this) ; //doesn't throws exception here
l = new JLabel() ;
l.setForeground(Color.red) ;
p.add(l) ;
p.add(cb) ;
f.add(p) ;
f.setVisible(true) ;
}
public void actionPerformed(ActionEvent ae){
if(cb.getSelectedItem() != null){
display() ;
}
}
private void display(){
String str = "" ;
str = "Combo selection changed to : " + cb.getSelectedItem() ;
l.setText(str) ;
System.out.println(str);
}
}
public class UseTest{
public static void main(String args[]){
Test t = new Test() ;
}
}
Solution
Everything works fine, the listener is correctly added to the JComboBox.
The thing is when you call addItem to the comboBox, the contentsChanged event is fired and your test#actionPerformed method is called which tries to do
l.setText(str);
But l is a JLabel that is initialized AFTER the cb.addItem loop. So when the event handler is called l is still null, thus the NullPointerException.
OTHER TIPS
Running your code, I get a NullPointerException in relation to your JLabel. This has not been initialised by the time the ActionListener is first called upon - when you add your first item is added and selection is therefore changed.
There's a good ComboBoxDemo
in How to Use Combo Boxes.
You may want to try adding an ItemListener instead.
Implementing ActionListener as you do is not a common pattern.
You should better code something like:
cb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
if((JComboBox)ae.getSource()).getSelectedItem() != null){
//Do your stuff
}
}
});