lecture8 oopj
DESCRIPTION
TRANSCRIPT
Java Event Handling
In AWT components, we came to know every component (except Panel and Label) generates events when interacted by the user like clicking over a button or pressing enter key etc. Listeners handle the events. Let us know the style (or design pattern) Java follows to handle the events.
The event handling involves three types of classes.
1. Event Sources2. Event classes3. Event Listeners
1. Event Sources
Event sources are components, subclasses of java.awt.Component, capable to generate events. The event source can be a button, TextField or a Frame etc.
java.awt.Component
After having the basic idea of Java AWT, let us know how many component classes exist with java.awt package.
2. Event classes
Almost every event source generates an event and is named by some Java class. For example, the button generates ActionEvent and Checkbox generates ItemEvent. All events listed in java.awt.event package. Following list gives a few components and their listeners.
3. Event Listeners
The events generated by the GUI components are handled by a special group of classes known as "listeners". Listener is an interface. Every component has its own listener, say, AdjustmentListener handles the events of scrollbar Some listeners handle the events of a few components. For example, ActionListener handles the events of Button, TextField, List and Menus. Listeners are from java.awt.event package.
Handle Action Events for AWT Button Example
import java.applet.Applet;import java.awt.Button;import java.awt.Graphics;import java.awt.event.ActionEvent;import java.awt.event.ActionListener; /*
<applet code="HandleActionEventExample" width=200 height=200></applet>*/ public class HandleActionEventExample extends Applet implements ActionListener{ String actionMessage=""; public void init() { //create Buttons Button Button1 = new Button("Ok"); Button Button2 = new Button("Cancel"); //add Buttons add(Button1); add(Button2); //set action listeners for buttons Button1.addActionListener(this); Button2.addActionListener(this); } public void paint(Graphics g) { g.drawString(actionMessage,10,50);
} public void actionPerformed(ActionEvent ae) { String action = ae.getActionCommand(); if(action.equals("Ok")) actionMessage = "Ok Button Pressed"; else if(action.equals("Cancel")) actionMessage = "Cancel Button Pressed"; repaint(); }
}