FAQ 3f
Updated: 1/7/00
>>>>>> How do I respond to Buttons and Stuff?
=============================================
The Applet has an action() function that you can overwrite.
This function is inherited from the Component class.
(Applet extends Container which extends Component).
public boolean action(Event e,Object o);
Here is a sample applet that uses the action() function:
// 'ActionApplet.java' code file
import java.applet.*;
import java.awt.*;
class ActionApplet extends Applet {
Button myButton
ActionApplet(){}
public void init(){
myButton = new Button("Press Me");
add(myButton);
}
public void paint(Graphics g){
g.drawString("Time In Milliseconds = "+System.getTimeMillis(),10,20);
}
public boolean action(Event e,Object o){
if (e.target==myButton) repaint();
return false;
}
}
As you can see, this applet will redisplay a millisecond counter every time you
press the button.
The value returned by the function indicates if the component's (ActionApplet's)
parent should recieve the event. The value TRUE means that your function has
consumed the event. The parent won't recieve the event in this case. The value
FALSE means that the event still exists and should move up the component tree.
see FAQ_2d to learn more about parents and component trees.
>>>>>> Advanced Action Handling
===============================
The method described above is the version 1.0 method. It still works, but has been
deprecated (declared old, someday won't be supported). The new method is to
use a ActionListener.
ActionListener is an interface, not a class. You can't extend an interface like
you can a class. You have to create a class, then implement the interface.
When you implement an interface, there will be some functions that you must write.
In the case of the ActionListener, there is one functions you have to include:
class MyActionHandler implements ActionListener {
public void actionPerformed(ActionEvent e){}
}
After you have your ActionListener, you need to tell the component (in this case the Button)
to talk to the ActionListener. You do this with the addActionListener() function. You usually
add the ActionListener directly to the component you want to track.
Here is the same applet as before, with a second class as the ActionListener:
// 'ActionApplet.java' code file
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
class ActionApplet extends Applet {
Button myButton;
KeyApplet(){}
public void init(){
myButton = new Button("Press Me");
myButton.addActionListener(new MyActionHandler(this));
add(myButton);
}
public void paint(Graphics g){
g.drawString("Time In Milliseconds = "+System.getTimeMillis(),10,20);
}
}
class MyActionHandler implements ActionListener {
Applet papa;
MyActionListener(Applet who){
papa = who;
}
public void actionPerformed(ActionEvent e){
papa.repaint();
}
}