Event Handling in Java
java programming and c, c++, Matlab, Python, HTML, CSS programming language, and new techniques news and any history.
java programming and c, c++, Matlab, Python, HTML, CSS programming language, and new techniques news and any history.
Event Handling
Any program that uses GUI (graphical user interface) such as Java application written for windows, is event-driven. The event describes the change of state of an object. Example:
Pressing a button, Entering a character in Textbox.
Components of Event Handling
Event handling has three main components,
- Events: An event is a change of state of an object.
- Events Source: Event source is an object that generates an event.
- Listeners: A listener is an object that listens to the event. A listener gets notified when an event occurs.
How Events are handled?
A source generates an Event and sends it to one or more listeners registered with the source. Once an event is received by the listener, they process the event and then return. Events are supported by a number of Java packages, like java.util, java.awt, and java.awt.event.
Important Event Classe and Interface
| Event Classe | Description | Listener Interface |
|---|---|---|
| ActionEvent | generated when the button is pressed, menu-item is selected, list-item is double-clicked | ActionListener |
| MouseEvent | generated when the mouse is dragged, moved, clicked, pressed or released also when he enters or exit a component | MouseListener |
| KeyEvent | generated when the input is received from keyboard | KeyListener |
| ItemEvent | generated when check-box or list item is clicked | ItemListener |
| TextEvent | generated when a value of textarea or text field is changed | TextListener |
| MouseWheelEvent | generated when the mouse wheel is moved | MouseWheelListener |
| WindowEvent | generated when a window is activated, deactivated, deiconified, iconified, opened or closed | WindowListener |
| ComponentEvent | generated when component is hidden, moved, resized or set visible | ComponentEventListener |
| ContainerEvent | generated when a component is added or removed from container | ContainerListener |
| AdjustmentEvent | generated when scrollbar is manipulated | AdjustmentListener |
| FocusEvent | generated when component gains or loses keyboard focus | FocusListener |
Example of Event Handling
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends Applet implements KeyListener
{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
HTML code :
< applet code="Test.html" width=300, height=100 >


Comments
Post a Comment