In Java, the ActionListener interface is used to detect and respond to events related to a component, such as a button click or menu item selection. In the context of applets, you can use an ActionListener to detect and respond to events that occur within the applet, such as a button click.
Here is an example code snippet that demonstrates how to use an ActionListener in an applet:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class MyButtonApplet extends Applet implements ActionListener {
private Button myButton;
public void init() {
myButton = new Button("Click me");
add(myButton);
myButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == myButton) {
// Code to handle button click goes here
System.out.println("Button clicked");
}
}
}
In this example, the applet creates a button component and adds an ActionListener to it using the addActionListener
method. The applet itself also implements the ActionListener interface, so it can handle the event when the button is clicked.
When the button is clicked, the actionPerformed
method is called, and the ActionEvent
object passed to it contains information about the event, such as the source of the event (in this case, the myButton
component).
In this example, the actionPerformed
method simply prints a message to the console indicating that the button was clicked. However, you can replace this code with any desired action that you want to perform in response to the button click event.
Comments