- What is an Event Handling and describe the components in Event Handling in Java?
- Components in Event Handling
- Events
- Event Sources
- Event Listeners
- Example
- SWING — Event Handling
- What is an Event?
- Types of Event
- What is Event Handling?
- Steps Involved in Event Handling
- Points to Remember About the Listener
- Callback Methods
- Event Handling Example
- A Java Event Represents a GUI Action in Java’s Swing GUI API
- How Events Work
- Types of Events
What is an Event Handling and describe the components in Event Handling in Java?
The GUI in Java processes the interactions with users via mouse, keyboard and various user controls such as button, checkbox, text field, etc. as the events. These events are to be handled properly to implement Java as an Event-Driven Programming.
Components in Event Handling
Events
- The events are defined as an object that describes a change in the state of a source object.
- The Java defines a number of such Event Classes inside java.awt.event package
- Some of the events are ActionEvent, MouseEvent, KeyEvent, FocusEvent,ItemEvent and etc.
Event Sources
- A source is an object that generates an event.
- An event generation occurs when an internal state of that object changes in some way.
- A source must register listeners in order for the listeners to receive the notifications about a specific type of event.
- Some of the event sources are Button, CheckBox, List, Choice, Window and etc.
Event Listeners
- A listener is an object that is notified when an event occurs.
- A Listener has two major requirements, it should be registered to one more source object to receiving event notification and it mustimplement methods to receive and process those notifications.
- Java has defined a set of interfaces for receiving and processing the events under the java.awt.event package.
- Some of the listeners are ActionListener, MouseListener, ItemListener, KeyListener, WindowListener and etc.
Example
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class EventListenerTest extends JFrame implements ActionListener < JButton button; public static void main(String args[]) < EventListenerTest object = new EventListenerTest(); object.createGUI(); >void createGUI() < button = new JButton(" Click Me !"); setSize(300,200); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); add(button); button.addActionListener(this); >public void actionPerformed(ActionEvent ae) < if(ae.getSource() == button) < JOptionPane.showMessageDialog(null, "Generates an Action Event"); >> >
SWING — Event Handling
In this chapter, you will learn about Events, its types, and also learn how to handle an event. Example is provided at the end of the chapter for better understanding.
What is an Event?
Change in the state of an object is known as Event, i.e., event describes the change in the state of the source. Events are generated as a result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from the list, and scrolling the page are the activities that causes an event to occur.
Types of Event
The events can be broadly classified into two categories −
- Foreground Events − These events require direct interaction of the user. They are generated as consequences of a person interacting with the graphical components in the Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page, etc.
- Background Events − These events require the interaction of the end user. Operating system interrupts, hardware or software failure, timer expiration, and operation completion are some examples of background events.
What is Event Handling?
Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has a code which is known as an event handler, that is executed when an event occurs.
Java uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.
The Delegation Event Model has the following key participants.
- Source − The source is an object on which the event occurs. Source is responsible for providing information of the occurred event to it’s handler. Java provide us with classes for the source object.
- Listener − It is also known as event handler. The listener is responsible for generating a response to an event. From the point of view of Java implementation, the listener is also an object. The listener waits till it receives an event. Once the event is received, the listener processes the event and then returns.
The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to a separate piece of code.
In this model, the listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listeners who want to receive them.
Steps Involved in Event Handling
Step 1 − The user clicks the button and the event is generated.
Step 2 − The object of concerned event class is created automatically and information about the source and the event get populated within the same object.
Step 3 − Event object is forwarded to the method of the registered listener class.
Step 4 − The method is gets executed and returns.
Points to Remember About the Listener
- In order to design a listener class, you have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods, which must be implemented by the listener class.
- If you do not implement any of the predefined interfaces, then your class cannot act as a listener class for a source object.
Callback Methods
These are the methods that are provided by API provider and are defined by the application programmer and invoked by the application developer. Here the callback methods represent an event method. In response to an event, java jre will fire callback method. All such callback methods are provided in listener interfaces.
If a component wants some listener to listen ot its events, the source must register itself to the listener.
Event Handling Example
Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingControlDemo < private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; public SwingControlDemo()< prepareGUI(); >public static void main(String[] args) < SwingControlDemo swingControlDemo = new SwingControlDemo(); swingControlDemo.showEventDemo(); >private void prepareGUI() < mainFrame = new JFrame("Java SWING Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); headerLabel = new JLabel("",JLabel.CENTER ); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); mainFrame.addWindowListener(new WindowAdapter() < public void windowClosing(WindowEvent windowEvent)< System.exit(0); >>); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); > private void showEventDemo() < headerLabel.setText("Control in action: Button"); JButton okButton = new JButton("OK"); JButton submitButton = new JButton("Submit"); JButton cancelButton = new JButton("Cancel"); okButton.setActionCommand("OK"); submitButton.setActionCommand("Submit"); cancelButton.setActionCommand("Cancel"); okButton.addActionListener(new ButtonClickListener()); submitButton.addActionListener(new ButtonClickListener()); cancelButton.addActionListener(new ButtonClickListener()); controlPanel.add(okButton); controlPanel.add(submitButton); controlPanel.add(cancelButton); mainFrame.setVisible(true); >private class ButtonClickListener implements ActionListener < public void actionPerformed(ActionEvent e) < String command = e.getActionCommand(); if( command.equals( "OK" )) < statusLabel.setText("Ok Button clicked."); >else if( command.equals( "Submit" ) ) < statusLabel.setText("Submit Button clicked."); >else < statusLabel.setText("Cancel Button clicked."); >> > >
Compile the program using the command prompt. Go to D:/ > SWING and type the following command.
D:\AWT>javac com\tutorialspoint\gui\SwingControlDemo.java
If no error occurs, it means the compilation is successful. Run the program using the following command.
D:\AWT>java com.tutorialspoint.gui.SwingControlDemo
Verify the following output.
A Java Event Represents a GUI Action in Java’s Swing GUI API
Paul Leahy is a computer programmer with over a decade of experience working in the IT industry, as both an in-house and vendor-based developer.
An event in Java is an object that is created when something changes within a graphical user interface. If a user clicks on a button, clicks on a combo box, or types characters into a text field, etc., then an event triggers, creating the relevant event object. This behavior is part of Java’s Event Handling mechanism and is included in the Swing GUI library.
For example, let’s say we have a JButton. If a user clicks on the JButton, a button click event is triggered, the event will be created, and it will be sent to the relevant event listener (in this case, the ActionListener). The relevant listener will have implemented code that determines the action to take when the event occurs.
Note that an event source must be paired with an event listener, or its triggering will result in no action.
How Events Work
Event handling in Java is comprised of two key elements:
- The event source, which is an object that is created when an event occurs. Java provides several types of these event sources, discussed in the section Types of Events below.
- The event listener, the object that «listens» for events and processes them when they occur.
There are several types of events and listeners in Java: each type of event is tied to a corresponding listener. For this discussion, let’s consider a common type of event, an action event represented by the Java class ActionEvent, which is triggered when a user clicks a button or the item of a list.
At the user’s action, an ActionEvent object corresponding to the relevant action is created. This object contains both the event source information and the specific action taken by the user. This event object is then passed to the corresponding ActionListener object’s method:
void actionPerformed(ActionEvent e)
This method is executed and returns the appropriate GUI response, which might be to open or close a dialog, download a file, provide a digital signature, or any other of the myriad actions available to users in an interface.
Types of Events
Here are some of the most common types of events in Java:
- ActionEvent: Represents a graphical element is clicked, such as a button or item in a list. Related listener: ActionListener.
- ContainerEvent: Represents an event that occurs to the GUI’s container itself, for example, if a user adds or removes an object from the interface. Related listener: ContainerListener.
- KeyEvent: Represents an event in which the user presses, types or releases a key. Related listener: KeyListener.
- WindowEvent: Represents an event relating to a window, for example, when a window is closed, activated or deactivated. Related listener: WindowListener.
- MouseEvent: Represents any event related to a mouse, such as when a mouse is clicked or pressed. Related listener: MouseListener.
Note that multiple listeners and event sources can interact with one another. For example, multiple events can be registered by a single listener, if they are of the same type. This means that, for a similar set of components that perform the same type of action, one event listener can handle all the events. Similarly, a single event can be bound to multiple listeners, if that suits the program’s design (although that is less common).