http://www.devshed.com/c/a/Java/Event-Handling-In-Java/
http://scatteredcode.wordpress.com/2011/11/24/from-c-to-java-events/
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.
You are leaving for work in the morning and someone rings the doorbell….
That is an event!
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. When the user interacts with a program let us say by clicking a command button, the system creates an event representing the action and delegates it to the event-handling code within the program. This code determines how to handle the event so the user gets the appropriate response.
In today’s tutorial we are going to learn event-driven programming, the event model of Java, and the different ways in which you can handle events.
Now lets taste our first cup of Java…
Components of an Event: Can be put under the following categories.
1. Event Object: When the user interacts with the application by clicking a mouse button or pressing a key an event is generated. The Operating System traps this event and the data associated with it. For example, info about time at which the event occurred, the event types (like keypress or mouse click). This data is then passed on to the application to which the event belongs. In Java, events are represented by objects, which describe the events themselves. And Java has a number of classes that describe and handle different categories of events.
2. Event Source: An event source is the object that generated the event. Example if you click a button an ActionEvent Object is generated. The object of the ActionEvent class contains information about the event.
3. Event-Handler: Is a method that understands the event and processes it. The event-handler method takes the Event object as a parameter. Java uses Event-Delegation Model :with JDK1.1 onwards; you can specify the objects that are to be notified when a specific event occurs. If the event is irrelevant, it is discarded. The four main components based on this model are Event classes, Event Listeners, Explicit event handling and Adapters. Let us take a closer look at them one by one.
Event Classes: The EventObject class is at the top of the event class hierarchy. It belongs to the java.util package. While most of the other event classes are present in java.awt.event package. The getSource() method of the EventObject class returns the object that initiated the event. The getId () method returns the nature of the event. For example, if a mouse event occurs, you can find out whether the event was click, a press, a move or release from the event object. AWT provides two conceptual types of events: Semantic and low-level events.
Semantic events are defined at a higher-level to encapsulate the semantics of user interface component’s model. Now let us see what are the various semantic event classes and what they generate:
• An ActionEvent object is generated when a component is activated
• An AdjustmentEvent Object is generated when scrollbars and other adjustment elements are used.
• A TextEvent object is generated when text of a component is modified.
• An ItemEvent is generated when an item from a list, a choice or checkbox is selected.
Low-Level Events is one that represents a low-level input or windows-system occurrence on a visual component on the screen. The various low-level event classes and what they generate are as follows:
• A ContainerEvent Object is generated when component are added or removed from container.
• A ComponentEvent object is generated when a component is resized, moved etc.
• A FocusEvent object is generated when component receives focus for input.
• A KeyEvent object is generated when key on keyboard is pressed, released etc.
• A WindowEvent object is generated when a window activity, like maximizing or close occurs.
• A MouseEvent object is generated when a mouse is used.
• A PaintEvent object is generated when component is painted.
Event Listeners: An object delegates the task of handling an event to an event listener. When an event occurs, an event object of the appropriate type (as illustrated below) is created. This object is passed to a Listener. A listener must implement the interface that has the method for event handling. A component can have multiple listeners, and a listener can be removed using removeActionListener () method. Next question in your mind must be what is an interface?. An Interface contains constant values and method declaration. The difference between classes and interface is that the methods in an interface are only declared and not implemented, that is, the methods do not have a body. What is the Need for interface? Are interfaces are used to define behavior protocols (standard behavior) that can be implemented by any class anywhere in the class hierarchy. The java.awt.event package contains definitions of all event classes and listener interface. The semantic listener interfaces define by AWT for the above mentioned semantic events are:
• ActionListener
• AjdustmentListener
• ItemListener
• TextListener
The low-level event listeners are as follows:
• ComponentListener
• ContainerListener
• FocusListener
• KeyListener
• MouseListener
• MouseMotionListener
• WindowsListener.
ActionEvent using the ActionListener interface: The following illustrates the usage of ActionEvent and ActionListener interface in a Classic Java Application (Example I).
//Save the file with MyEvent.java file and compile it using javac, //once complied errors free execute it. Import javax.swings.*; Import java.awt.event.*; Public class MyEvent extends JFrame { JButton b1; // Main Method Public static void main (String arg[]) { MyEvent event = new MyEvent(); } //Constructor for the event derived class Public MyEvent() { Super(“Window Title: Event Handling”); b1 = new Jbutton(“Click Me”); //place the button object on the window getContentPane().add(“center”,b1); //Register the listener for the button ButtonListener listen = new ButtonListener(); b1.addActionListener(listen); //display the window in a specific size setVisible(true); setSize(200,200); } //The Listener Class Class ButtonListener implements ActionListener { //Definition for ActionPerformed() method Public void ActionPerformed(ActionEvent evt) { JButton source = (JButton)evt.getSource(); Source.setText(“Button Has Been Clicked, Guru!”); } } }How does the above Application work?
• The execution begins with the main method.
• An Object of the MyEvent class is created in the main method.
• Constructor of the MyEvent class is invoked.
• Super () method calls the constructor of the base class and sets the title of the window as given.
• A button object is created and placed at the center of the window.
• A Listener Object is created.
• The addActionListener() method registers the listener object for the button.
• SetVisible () method displays the window.
• The Application waits for the user to interact with it.
• When the user clicks on the button labeled “Click Me”: The “ActionEvent” event is generated. Then the ActionEvent object is created and delegated to the registered listener object for processing. The Listener object contains the actionPerformed() method which processes the ActionEvent In the actionPerformed() method, the reference to the event source is retrieved using getSource() method. The label of the button is changed to “Button has been clicked, Guru!” using setText() method.
• Tools of the Trade: Since the ButtonListener class has been declared under MyEvent class. Therefore ButtonListener class is an inner class.
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.
Mouse Events, MouseListener and MouseMotionListener:
These are generated when a mouse is moved, clicked, pressed and released etc. The MouseEvent class represents these events as six constant values and has methods to get the co-ordinates at which a mouse event occurred. The mouse move and mouse drag are treated differently from the rest four mouse pressed, mouse released, mouse entered and mouse exited. Hence there are two types of mouse event listeners- MouseListener and MouseMotionListener.
The following code illustrates the usage of mouse event listeners. Watch out for messages on the status line of applet as and when the user performs a mouse event. (Example 3 also shows the co-ordinates at which the event occurred.
// Example 3: MouseEvents & MouseListener /* <Applet code = "mouseEvent.class" height= 400 width = 400 > </applet> */ Import java.awt.*; Import java.awt.event.*; Import javax.swing.*; Public class mouseEvent extends JApplet implements MouseListener, MouseMotionListener { Public void init() { addMouseListener(this); addMouseMotionListener(this); } Public void mouseClicked(MouseEvent e) { showStatus("Mouse has been clicked at " + e.getX()+ "," + e.getY()); } Public void mouseEntered(MouseEvent e) { showStatus("Mouse has been Entered at " + e.getX()+ "," + e.getY()); // For loop:to make sure mouse entered is on status bar for a few sec For (int i= 0; i<1000000; i++); } Public void mouseExited (MouseEvent e) { showStatus ("Mouse has been Exited at " + e.getX()+ "," + e.getY()); } Public void mousePressed(MouseEvent e) { showStatus ("Mouse pressed at " + e.getX()+ "," + e.getY()); } Public void mouseReleased(MouseEvent e) { showStatus("Mouse released at " + e.getX()+ "," + e.getY()); } Public void mouseDragged(MouseEvent e) { showStatus("Mouse dragged at " + e.getX()+ "," + e.getY()); } Public void mouseMoved(MouseEvent e) { showStatus("Mouse moved at " + e.getX()+ "," + e.getY()); } }Since the applet implements MouseListener and
MouseMotionListener it has to provide for the functionality of all their methods. Observe the mouseEntered() method has a small loop to ensure the mouse entered message remains on the status bar for a while. {mospagebreak title=Key Frienldy Codes} Keyboard Events and KeyListener: They are generated on pressing or releasing a key. The KeyEvent class contains constants to represent the keys pressed or typed. The event listener corresponding to these types of event is the KeyListener.
The following example puts forth key event handling. The applet contains a label and a text field. The recently typed in character in the text field is displayed in the status bar. Example 4.
// Key events and KeyListener. /* <applet code = "keyTest.class" width = 400 height = 400> </applet> */ Import java.awt.*; Import java.awt.event.*; Import java.applet.Applet; Public class keyTest extends Applet implements KeyListener { Public void init() { Label lab = new Label ("Enter Characters :"); add(lab); TextField tf = new TextField(20); add(tf); tf.addKeyListener(this); } Public void keyPressed(KeyEvent e) {} Public void keyReleased(KeyEvent e) {} Public void keyTyped(KeyEvent e) { showStatus(" Recently typed characters are : " + e.getKeyChar()); } }Here the text field delegates its key events to the
applet. The add() method adds the components Label and TextField to the applet.
A quick recap: Every time the user types a character or pushes a mouse button, an event occurs. Any object can be notified of the event. All it has to do is implement the appropriate interface and be registered as an event listener on the appropriate event source. Swing components can generate many kinds of events.
Each event is represented by an object that gives information about the event and identifies the event source. Event sources are typically components, but other kinds of objects can also be event sources. Each event source can have multiple listeners registered on it. Conversely, a single listener can register with multiple event sources.
In the next part of the tutorial we will see about Explicit Event-handling and adapters.