Below is the source code for UseTest.java :-
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() ;
}
}