In life, you encounter events that force you to suspend other activities and respond to them immediately. In Java, events represent all activity that goes on between the user and the application. Java's Abstract Windowing Toolkit (AWT) communicates these actions to the programs using events.
For those of you folks who are more into using Java Applets here is easy sample which works.Type in the following code (Example 2) and save it as ButtonEvent.java and the compile using javac and view it using appletviewer. A short cut to avoid compiling a java file and html file separately you can enclose the applet tag normally containing applet code, height, width, param tags etc. within /* and */. Then compile as one single file, because the HTML tag will be read as html automatically. And when compiled error free run using Appletviewer tag.
/*
<Applet code = "ButtonEvent.class" height = 400 width = 400>
</applet>
*/
Import java.awt.*;
Import java.awt.event.*;
Import java.applet.Applet;
Public class ButtonEvent extends Applet implements ActionListener
{
Private Button b;
Public void init() {
b = new Button("Click me");
b.addActionListener(this);
add (b);
}
Public void actionPerformed (ActionEvent e) {
// If the target of the event was our Button
// In this example, the check is not
// Truly necessary as we only listen to
// A single button
If (e.getSource () == b) {
getGraphics().drawString("OUCH Buddy",20,20);
}
}
}
The above sample code pretty much does the same thing
as Example I only the applet starts with the init() method first the button is added using the add() method and is registered with ActionListener(). Once the user clicks it, The event is trapped using the getSource() and delegated to the appropriate listener. The getGraphics() method of the image class is used along with drawString() method to draw the text given by the specified string.