|
Previous Next
Item Listener
In this example, we will show how to use the ItemListener interface to respond to the JComboBox components.
We create a class called SelectState as an extension of the JFrame class. With it, we implement the ItemListener interface which contains the method, itemStateChanged.
After we create the JComboBox component, we use the addItemListener method to attach the ItemListener to it.
We use the method addItem to build the list of selections. We prevent the user from being able to add anything else to the list by using setEditable(false).
In the method, itemStateChanged(ItemEvent evt), the evt represents the event that happened. The getItem method of the event will pick up the selected item. We convert the choice to a String and display it in the text field.
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class SelectState extends JFrame implements ItemListener {
JLabel lbl= new JLabel("My State:");
JTextField txt = new JTextField(15);
JComboBox choices = new JComboBox();
String[] states = {"Alabama (AL)", "Alaska (AK)", "Arizona (AZ)",
"Arkansas (AR)", "Washington (WA)", "West Virginia (WV)",
"Wisconsin (WI)", "Wyoming (WY)"};
public SelectState() {
super("Choose your state");
setSize(250, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
choices.addItemListener(this);
choices.addItem("unknown");
choices.addItem("non-USA");
for (int i = 0; i < 4; i++) {
choices.addItem(states[i]);
}
choices.addItem("...");
for (int i = 4; i < 8; i++) {
choices.addItem(states[i]);
}
choices.setEditable(false);
JPanel pane = new JPanel();
pane.add(lbl);
pane.add(txt);
pane.add(choices);
setContentPane(pane);
}
public static void main(String[] arguments) {
SelectState ss = new SelectState();
ss.setVisible(true);
}
public void itemStateChanged(ItemEvent evt) {
Object chosen = evt.getItem();
txt.setText(chosen.toString());
}
}
Previous Next
|