Action Listeners
Action Listeners are how Java determines whether or not a button has been pressed. You set each button to have a unique "actionCommand" which identifies which button was clicked. (You can also have mouse Listeners and window listeners and others...). When an action occurs, and a button is clicked, Java runs the code in actionPerformed. An if is set up in this method to run the appropriate code for each button.
Init Method Code
| Silly Fire Station Story | Code Description | Code |
| The subdivision plans are drawn up. | Get the right libraries, extend the class corectly. | import java.awt.*; import java.awt.event.*; import javax.swing.* public class RockPaperScissors extends Applet implements ActionListener |
| The individual house plans are drawn up.. | Buttons are Declared | JButton b1; |
| Construction begins. | Construction. | b1=new JButton("Hi"); |
| Contractor phones fire station and sets up a special signal for each building so the fire trucks go to the right house. | Set specific action command for each button. | b1.setActionCommand ("Hi"); |
| Smoke detectors are installed in each house. | Add the action listeners. |
b1..addActionListener (this); don't forget implements ActionListener. |
| Finish the house, sell it to a happy family. | Add the button to the applet. | add(b1); |
ActionPerformed Method Code.
| Silly Fire Station Story | Code Description | Code |
| A three year old gets the matches and starts a fire. | Button Clicked | - |
| Smoke alarm alerts the fire station. Address is passed with alarm. | The button listener catches it and sends a command to java that an event has occured. It passes the ActionCommand for that button - the string "Hi" in this case. | ActionPerformed Method is started. |
| Fire fighters go the the right house and save the 3 year old. | Code in actionPerformed is run. The string in
e.getActionCommand is used to determine the code to run. Print Hi in the status bar in this instance. |
public void actionPerformed (ActionEvent e) { if (e.getActionCommand ().equals ("Hi")) {showStatus("Hi"); } |