Event Handling in Java Swing
In Java Swing, event handling is crucial for responding to user interactions like button clicks. Learn how to create event listeners and process events triggered by buttons in your GUI applications. This tutorial provides a step-by-step guide with code examples to understand the ActionListener interface and how to register listener objects with event source objects.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Introduction To respond to a button click, you need to write the code to process the button-clicking action. The button is an event source object, where the action originates. You need to create an object capable of handling the action event on a button. This object is called an event listener, as shown in the following Figure. Triggering a source fires an event to all its listener(s), and invoke an appropriate event handler of the listener(s). 2
Introduction The object must be an instance of the ActionListener interface. The ActionListener object listener must be registered with the event source object using the method source.addActionListener(listener). The ActionListener actionPerformed method for processing the event. Your listener class must override this method to respond to the event. The following program gives the code that processes the ActionEvent on the two buttons (Ok and Cancel). interface contains the 3
Introduction import javax.swing.*; import java.awt.event.*; public class HandleEvent extends JFrame{ public HandleEvent() { // Create two buttons JButton jbtOK = new JButton("OK"); JButton jbtCancel = new JButton("Cancel"); // Create a panel to hold buttons JPanel panel = new JPanel(); panel.add(jbtOK); panel.add(jbtCancel); Create Listener add(panel); // Add panel to the frame // Register listeners OkListenerClass listener1 = new OkListenerClass(); CancelListenerClass listener2 = new CancelListenerClass(); jbtOK.addActionListener(listener1); jbtCancel.addActionListener(listener2); } Register Listener 4
Introduction public static void main(String[] args) { JFrame frame = new HandleEvent(); frame.setTitle("Handle Event"); frame.setSize(200, 150); frame.setLocation(200, 100); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } class OkListenerClass implemets ActionListener{ @Override public void actionPerformed(ActionEvent e) { System.out.println("OK button clicked"); } } Process Event Listener Class Listener Class class CancelListenerClass implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { System.out.println("Cancel button clicked"); } } Process Event 5
Introduction The above program defines two listener classes. Each listener class implements ActionListener to process ActionEvent. The object listener1 is an instance of OKListenerClass, which is registered with the button jbtOK. When the OK button is clicked, the actionPerformed(ActionEvent) method in OKListenerClass is invoked to process the event. The object listener2 is an instance of CancelListenerClass, which is registered with the button jbtCancel. When the Cancel button is clicked, the actionPerformed(ActionEvent) method in CancelListenerClass is invoked to process the event. 6
Events and Event Sources An event is an object created from an event source. Firing an event means to create an event and delegate the listener to handle the event. When you run a Java GUI program, the program interacts with the user, and the events drive its execution. This is called event-driven programming. An event can be defined as a signal to the program that something has happened. Events are triggered either by external user actions, such as mouse movements, button clicks, and keystrokes, or by internal program activities, such as a timer. The program can choose to respond to or ignore an event. 7
Events and Event Sources The component that creates an event and fires it is called the event source source object or source component. object, or simply For example, a button is the source object for a button clicking action event. An event is an instance of an event class. The root class java.util.EventObject. of the event classes is 8
Event Classes The hierarchical relationships of some event classes. 9
Event Information An event object contains whatever properties are pertinent to the event. You can identify the source object of the event using the getSource() instance method in the EventObject class. The subclasses of EventObject deal with special types of events, such as button actions, window events, component events, mouse movements, and keystrokes. Following table lists external user actions, source objects, and event types generated. 10
Selected User Actions User Action Source Object Event Type Generated Click a button Click a check box Click a radio button Press return on a text field Select a new item Window opened, closed, etc. Mouse pressed, released, etc. Key released, pressed, etc. JButton JCheckBox JRadioButton JTextField JComboBox Window Component Component ActionEvent ItemEvent, ActionEvent ItemEvent, ActionEvent ActionEvent ItemEvent, ActionEvent WindowEvent MouseEvent KeyEvent 11
Listener, Registrations and Handling Events A listener is an object that must be registered with an event source object, and it must be an instance of an appropriate event-handling interface. Java uses a delegation-based model for event handling: a source object fires an event, and an object interested in the event handles it. 12
The Delegation Model The listener object must be an instance of the corresponding event-listener interface to ensure that the listener has the correct method for processing the event. The listener interface is usually named XListener for XEvent, with the exception of MouseMotionListener. The listener interface contains the method(s), known as the event handler(s), for processing the event. For example, as shown in the first line of the above table, the corresponding listener interface ActionListener; each listener for ActionEvent should implement the ActionListener interface; the ActionListener interface contains the handler actionPerformed(ActionEvent) processing an ActionEvent. for ActionEvent is for 14
The Delegation Model The listener object must be registered by the source object. Registration methods depend on the event type. For ActionEvent, addActionListener. In general, the method is named addXListener for XEvent. the method is 15
The Delegation Model: Example JButton jbtOk = new JButton("OK"); OKListenerClass listener = new OKListenerClass(); jbtOk.addActionListener(listener); 17
Selected Event Handlers Listener Interface Event Class Listener Methods (Handlers) ActionEvent ItemEvent WindowEvent ContainerEvent MouseEvent KeyEvent ActionListener ItemListener WindowListener ContainerListener MouseListener actionPerformed(ActionEvent) itemStateChanged(ItemEvent) windowClosing(WindowEvent) windowOpened(WindowEvent) windowIconified(WindowEvent) windowDeiconified(WindowEvent) windowClosed(WindowEvent) windowActivated(WindowEvent) windowDeactivated(WindowEvent) componentAdded(ContainerEvent) componentRemoved(ContainerEvent) mousePressed(MouseEvent) mouseReleased(MouseEvent) mouseClicked(MouseEvent) mouseExited(MouseEvent) mouseEntered(MouseEvent) keyPressed(KeyEvent) keyReleased(KeyEvent) keyTypeed(KeyEvent) KeyListener 18
Inner Class Listeners An inner class, or nested class, is a class defined within the scope of another class. Inner classes are useful for defining listener classes. A listener class is designed specifically to create a listener object for a GUI component (e.g., a button). It will not be shared by other applications. So, it is appropriate to define the listener class inside the frame class as an inner class. 20
Inner Class Listeners An inner class has the following features: An inner class supports the work of its containing outer class and is compiled into OuterClassName$InnerClassName.class. For example, the inner class InnerClass in OuterClass is compiled into OuterClass$InnerClass.class. a class named An inner class can reference the data and methods defined in the outer class in which it nests, so you need not pass the reference of an object of the outer class to the constructor of the inner class. Inner classes can make programs simple and concise. An inner class can be declared public, protected, or private subject to the same visibility rules applied to a member of the class. 21
Inner Class Listeners An inner class can be declared static. A static inner class can be accessed using the outer class name. A static inner class cannot access non-static members of the outer class. Objects of an inner class are often created in the outer class. But you can also create an object of an inner class from another class. If the inner class is non-static, you must first create an instance of the outer class, then use the following syntax to create an object for the inner class: OuterClass.InnerClass innerObject = outerObject.new InnerClass(); If the inner class is static, use the following syntax to create an object for it: OuterClass.InnerClass innerObject = new OuterClass.InnerClass(); 22
Anonymous Inner Classes An anonymous inner class is an inner class without a name. It combines defining an inner class and creating an instance of the class into one step. Inner-class listeners can be shortened using anonymous inner classes. An anonymous inner class is declared as follows: new SuperClassName/InterfaceName(){ // Implement or override methods in superclass or interface // Other methods if necessary } 24
Anonymous Inner Classes (cont.) Anonymous inner class is a special kind of inner class with the following features: An anonymous inner class must always extend a superclass or implement an interface, but it cannot have an explicit extends or implements clause. An anonymous inner class must implement all the abstract methods in the superclass or in the interface. An anonymous inner class always uses the no-arg constructor from its superclass to create an instance. If an anonymous inner class implements an interface, the constructor is Object(). An anonymous inner class is compiled into a class named OuterClassName$n.class. For example, if the outer class Test has two anonymous inner classes, these two classes are compiled into Test$1.class and Test$2.class. 25
Example: Anonymous Inner Classes import javax.swing.*; import java.awt.event.*; public class AnonymousClass extends JFrame { public AnonymousClass() { // Create four buttons JButton jbtNew = new JButton("New"); JButton jbtOpen = new JButton("Open"); JButton jbtSave = new JButton("Save"); JButton jbtPrint = new JButton("Print"); // Create a panel to hold buttons JPanel panel = new JPanel(); panel.add(jbtNew); panel.add(jbtOpen); panel.add(jbtSave); panel.add(jbtPrint); add(panel); // Create and register anonymous inner-class listener jbtNew.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ System.out.println("Process New"); } } ); 27
Example: Anonymous Inner Classes jbtOpen.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Process Open"); } } ); jbtSave.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Process Save"); } } ); jbtPrint.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Process Print"); } } ); } public static void main(String[] args) { JFrame frame = new AnonymousClass(); frame.setTitle("Anonymous Listener Demo"); frame.setLocationRelativeTo(null ); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); //automatically sizes the frame frame.setVisible(true); } } 28
Example: Anonymous Inner Classes The program creates four listeners using anonymous inner classes. Without using anonymous inner classes, you would have to create four separate classes. An anonymous listener works the same way as an inner class listener. The program is condensed using an anonymous inner class. Anonymous inner classes are compiled into OuterClassName$#.class, where # starts at 1 and is incremented for each anonymous class the compiler encounters. In this example, the anonymous inner classes are compiled into AnonymousClass$1.class, AnonymousClass$2.class, AnonymousClass$3.class, AnonymousClass$4.class. Instead of using the setSize method to set the size for the frame, the program uses the pack() method, which automatically sizes the frame according to the size of the components placed in it. 29
Mouse Event A mouse event is fired whenever a mouse button is pressed, released, or clicked, the mouse is moved, or the mouse is dragged onto a component. The MouseEvent object captures the event, such as the number of clicks associated with it, the location (the x- and y-coordinates) of the mouse, or which button was pressed, as shown in the following class diagram . 30
Mouse Event 31
Mouse Event Since the MouseEvent class inherits InputEvent, you can use the methods defined in the InputEvent class on a MouseEvent object. For example, the isControlDown() method detects whether the CTRL key was pressed when a MouseEvent is fired. Three int constants BUTTON1, BUTTON2, and BUTTON3 are defined in MouseEvent to indicate the left, middle, and right mouse buttons. You can use the getButton() method to detect which button is pressed. For example, getButton() == MouseEvent.BUTTON3 indicates that the right button was pressed. 32
Handling Mouse Events Java MouseListener andMouseMotionListener, to handle mouse events. provides two listener interfaces, TheMouseListenerlistens for actions such as when the mouse is pressed, released, entered, exited, or clicked. TheMouseMotionListenerlistens for actions such as dragging or moving the mouse. 33
Handling Mouse Events The MouseListener interface handles mouse pressed, released, clicked, entered, and exited events. TheMouseMotionListener interface handles mouse dragged and moved events. 34
Example: Moving Message Using Mouse Objective: Create a program to display a message in a panel. You can use the mouse to move the message. The message moves as the mouse drags and is always displayed at the mouse point. 35
Example: Moving Message Using Mouse import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MoveMessageDemo extends JFrame { public MoveMessageDemo() { // Create a MovableMessagePanel instance for moving a message MovableMessagePanel p = new MovableMessagePanel("Welcome to Java"); // Place the message panel in the frame add(p); } /** Main method */ public static void main(String[] args) { MoveMessageDemo frame = new MoveMessageDemo(); frame.setTitle("MoveMessageDemo"); frame.setSize(200, 100); frame.setLocationRelativeTo(null ); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } 36
Example: Moving Message Using Mouse // Inner class: MovableMessagePanel draws a message static class MovableMessagePanel extends JPanel { private String message = "Welcome to Java"; private int x = 20; private int y = 20; /** Construct a panel to draw string s */ public MovableMessagePanel(String s) { message = s; addMouseMotionListener(new MouseMotionListener() { @Override /** Handle mouse-dragged event */ public void mouseDragged(MouseEvent e) { // Get the new location and repaint the screen x = e.getX(); y = e.getY(); repaint(); } }); } @Override /** Handle mouse-moved event */ public void mouseMoved(MouseEvent e) { } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawString(message, x, y); } } } 37
Code Description The MovableMessagePanel class extends JPanel to draw a message. Additionally, it handles redisplaying the message when the mouse is dragged. This class is defined as an inner class inside the main class because it is used only in this class. Furthermore, the inner class is defined as static because it does not reference any instance members of the main class. The MouseMotionListener interface contains two handlers, mouseMoved and mouseDragged, for handling mouse-motion events. 38
Code Description When you move the mouse with a button pressed, the mouseDragged method is invoked to repaint the viewing area and display the message at the mouse point. When you move the mouse without pressing a button, the mouseMoved method is invoked. Because the listener is interested only in the mouse-dragged event, the mouseDragged method is implemented. The mouseDragged method is invoked when you move the mouse with a button pressed. This method obtains the mouse location using the getX and getY methods in the MouseEvent class. This becomes the new location for the message. Invoking the repaint() method causes paintComponent to be invoked, which displays the message in a new location. 39
Key Events A key event is fired whenever a key is pressed, released, or typed on a component. Key events enable the use of the keys to control and perform actions or get input from the keyboard. 40
Handling Keyboard Events To process a keyboard event, use the following handlers in theKeyListenerinterface: keyPressed(KeyEvent e)Called when a key is pressed. keyReleased(KeyEvent e) Called when a key is released. Called when a key is pressed keyTyped(KeyEvent e) and then released. These methods are used for processing the Key event. 41
TheKeyEventClass Methods: getKeyChar() method getKeyCode() method Keys: Home End Page Up Page Down etc... VK_HOME VK_END VK_PGUP VK_PGDN 42
The End 43