xhtml
 

Listening to Events

Which object in your program should respond to a button press?  For a simple program, the answer might be the program object.  This leads to a program like this, which counts the number of times you press the button:

PressCount.java
...
import java.awt.event.*;

class PressCount implements Runnable, ActionListener
{
   int numberOfPresses;
   JLabel counter;
...
      JButton button = new JButton("Press");
      button.addActionListener(this);
...
   public void actionPerformed(ActionEvent e)
   {
      numberOfPresses++;
      counter.setText("" + numberOfPresses);
   }
...

This program, as with any interactive graphics program, has to import the java.awt.event package.  The program class itself implements the ActionListener interface by providing the actionPerformed method.  The program object (referred to as this since it is the current object) is given to the button as a listener object.

The actionPerformed method is not called from anywhere in your own code.  It is called by the button object.  The code in the button object is executed by the implicit graphics thread that is started up whenever you begin using graphics, and which continues after the main method ends.

Since the actionPerformed method is called by the graphics thread, the method should be quick, and should not involve sleep calls or other delays. Otherwise, the speed of graphics updating or of interaction will be affected.  If there is a long calculation to do or a delay is needed, this will have to be handled by a non-graphics thread -- either the main program thread or another one that you create for the purpose.


Back