ActionListener

ActionListeners are used to respond to action events. Action events are typically created by clicking a button or pressing return in a text field. The ActionListener interface consists of a single method, actionPerformed. Specifically, this method has the signature

void actionPerformed(ActionEvent e);

where e is an object of type ActionEvent. The java.awt.event.ActionEvent class contains a number of methods; two of the most useful are getSource and getActionCommand. getSource returns the object that generated the event. getActionCommand returns the command string associated with the component that generated the event. By default, this string is the text associated with a labeled component; you can explicitly set the command string using the setActionCommand method.

As an example, suppose we have registered action listeners for a combo box, freqButton, and a radio button group, age, consisting of individual radio buttons age1, age2, age3, and age4. These could represent the shopping frequency combo box and age radio button in the Customer Details screen of Figure 8.1. The actionPerformed method is shown next.
actionPerformed

public void actionPerformed(ActionEvent e)
{
if (e.getSource() instanceof JComboBox)
{
System.out.println(''Customer shops : " +
freqButton.getSelectedItem() );
}
else if (e.getSource() instanceof JRadioButton)
{
if (age1.isSelected() )
{
System.out.println("Customer is under 20");
} else if (age2.isSelected() ) {
System.out.println("Customer is 20 - 39");
} else if (age3.isSelected() ) {
System.out.println("Customer is 40 - 59");
} else if (age4.isSelected() ) {
System.out.println("Customer is over 60");
}
}
}

If the user clicks the freqButton combo box, a message is printed to the console informing us how frequently the customer shops. Since we have also registered an action listener for the age radio button, the statement (line 2)

if (e.getSource() instanceof JComboBox) {

determines whether the event corresponds to the clicking of a combo box. Since the application is registered to listen to only one combo box, freqButton, we can use the javax.swing. JComboBox.getSelectedItem method to determine the currently selected item.

In line 5, we check if the event corresponds to the user clicking a radio button. In line 6, we use the javax.swing.JCheckBox.isSelected method to determine if the age1 radio button has been selected. The isSelected method returns true if the radio button is currently selected, otherwise false. We perform similar tests for the remaining radio buttons forming the radio button group.

No comments:

Post a Comment