Java Reference
In-Depth Information
actionPerformed method is added to the viewer class. That is, the viewer
implements the ActionListener interface.
public class InvestmentViewer
implements ActionListener // This approach is not
recommended
{
public InvestmentViewer()
{
JButton button = new JButton("Add Interest");
button.addActionListener(this);
. . .
}
public void actionPerformed(ActionEvent event)
{
}
. . .
}
417
418
Now the actionPerformed method is a part of the InvestmentViewer
class rather than part of a separate listener class. The listener is installed as this .
This technique has two major flaws. First, it separates the button definition from
the button action. Also, it doesn't scale well. If the viewer class contains two
buttons that each generate action events, then the actionPerformed method
must investigate the event source, which leads to code that is tedious and
error-prone.
9.9 Processing Timer Events
In this section we will study timer events and show how they allow you to implement
simple animations.
The Timer class in the javax.swing package generates a sequence of action
events, spaced apart at even time intervals. (You can think of a timer as an invisible
button that is automatically clicked.) This is useful whenever you want to have an
object updated in regular intervals. For example, in an animation, you may want to
update a scene ten times per second and redisplay the image, to give the illusion of
movement.
Search WWH ::




Custom Search