|
Event
Handling Details
The following modifications are required for the generic applet to
include the event handling from user actions. For now, we will proceed
with the assumption that the applet itself will handle the events.
- Modifying the applet declaration
The declaration of the applet seen so far had the following
syntax:
public class TestApplet extends JApplet
For the applet to behave as the event handler, the declation is modified as follows:
public class TestApplet extends JApplet
implements <one or more Listeners>
For example, to respond to button events, the applet declaration would be:
public class TestApplet extends JApplet
implements ActionListener
To respond to slider (scroll) events, the applet declaration would be:
public class TestApplet extends JApplet
implements ChangeListener
To respond to mouse motion events, the applet declaration would be:
public class TestApplet extends JApplet
implements MouseMotionListener
In case the applet needs to respond to multiple types of events, say buttons and mouse events, the applet
declaration implements all the required listeners:
public class TestApplet extends JApplet
implements ActionListener,
MouseMotionListener
- Adding listeners to the components
The next step, once the GUI components (buttons, text fields, etc.) are created, is to add the
appropriate listeners. The following are some examples of listeners for buttons, slider, and for the
applet itself.
button.addActionListener(this);
slider.addChangeListener(this);
this.addMouseMotionListener(this);
In the first case, an action listener is added to variable named button (of type JButton).
In the second case, a change listener is added to the variable named slider (of type JSlider).
In the last case, the mouse motion listener is added to the applet itself, refered to by the variable this.
The argument to the listener in all the above cases is the applet itself (hence the value this).
- Event handling method definitions
Depending upon the listener implemented by the applet, the code for the corresponding event handling
methods need to be implemented by the applet. For button event handling, the following method definition is
required as part of the applet code:
public void actionPerformed(ActionEvent e) {
// code to respond to the button
}
Whenever a button click occurs, the above method is automatically invoked. The argument for the method
details the type of the event and the details asscoiated with the event. When there is only one button
as in the previous program, we obviously know the source of the event.
|