PROGRAM-9
PROGRAM-9
Aim:- Write a applet for event handling which prints a message when Clicked on button.
Overview;
In Java applets, event handling was an essential aspect that enabled user interaction with the
applet. Java’s event-handling model allows applets to respond to various actions, such as mouse
clicks, keyboard inputs, and other user interactions. Event handling in applets follows the
listener-based model, where an event (e.g., mouse click) triggers a method in a listener object
that responds to that event.
Event-Driven Programming:
• Java applets are designed to be event-driven, meaning they don't continually run in a
loop. Instead, they respond to events such as user actions (mouse movements, clicks,
key presses) or system-generated events (e.g., window resizing).
• When an event occurs, the appropriate event handler method is called automatically.
Event Sources:
• In Java applet event handling, the event source is the object that generates the event.
For example, a button, a text field, or the applet’s graphical area (canvas) could act as
the event source.
Event Listeners:
• To handle events, applets must register an event listener, which is a Java interface that
defines methods to handle specific events. For example, the MouseListener interface
handles mouse events, and the KeyListener interface handles keyboard events.
• Event listeners listen for a specific event and, when that event occurs, call the
corresponding handler method.
• Registering Listeners: First, the applet must register the appropriate listener(s) with
the event source. For example, if you want to respond to a mouse click on a button, you
register a MouseListener with that button.
• Event Occurrence: When an event occurs (e.g., the user clicks the button), the event
source triggers an event.
• Listener Response: The listener, which has been registered to listen for that specific
event, invokes the corresponding method (e.g., mouseClicked() for mouse click events).
• Event Handling Method: The applet contains the method(s) defined in the listener
interfaces (e.g., mouseClicked() for mouse events), and the applet performs the desired
action (such as drawing a shape, changing text, or printing a message) in response.
Code
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
javax.swing.JOptionPane;
frame.setSize(300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new ActionListener() {
});
frame.add(button); frame.setVisible(true);
}}
OUTPUT