Java Reference
In-Depth Information
1. Create a class implementing the interface ActionListener .
2. Provide the definition of the method actionPerformed .
3. Create and instantiate an object, action listener, of the class type
created in Step 1.
4. Register the listener of Step 3 to each button.
In Chapter 6, we created a separate class for each of the buttons and then created a
separate listener for each button. In this new program, rather than create a separate
class for each button, we create only one class. Recall that the heading of the method
actionPerformed is:
public void actionPerformed(ActionEvent e)
In Chapter 6, while providing the definition of this method, we ignored the formal
parameter e . The formal parameter e is a reference variable of the ActionEvent
type. The class ActionEvent contains getActionCommand (a method without
parameters), which can be used to identify which button generated the event. For
example, the expression:
e.getActionCommand()
returns the string containing the label of the component generating the event. We can
now use the appropriate String method to determine the button generating the event.
If the user clicks on one of the product buttons, then the candy machine attempts to
sell the product. Therefore, the action of clicking on a product button is to sell. For
this, we write the method sellProduct (discussed later in this programming
example). If the user clicks on the Exit button, the program should terminate. Let's
call the class to handle these events ButtonHandler . Its definition is:
private class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
if (e.getActionCommand().equals("Exit"))
System.exit(0);
else if (e.getActionCommand().equals("Candy"))
sellProduct(candy, "Candy");
else if (e.getActionCommand().equals("Chips"))
sellProduct(chips, "Chips");
else if (e.getActionCommand().equals("Gum"))
sellProduct(gum, "Gum");
else if (e.getActionCommand().equals("Cookies"))
sellProduct(cookies, "Cookies");
}
}
 
Search WWH ::




Custom Search