23
2011
Event Handlers in Java
In my previous stone, I taught you how to create a simple GUI in Java, but that interface did practically nothing. It was merely a skeleton interface which I showed you so that you would learn the basics of creating User Interfaces in Java. In this stone we continue where we left off on the last stone, if you haven’t yet gone through my previous post on the basics of creating a GUI I suggest you do; before you start trying to understand what I have done here. This stone will show you how to make the User Interface do your bidding using Java’s awesome event handler.
Before beginning our discussion of event handling, an important point must be made: The way in which events are handled has changed significantly between the original version of Java (1.0) and modern versions of Java beginning with version 1.1. Even though the older method is still supported the modern approach is the way, events should be handled by all new programs and it is the method I will be using in this tutorial.
The modern approach to handling events is based on something called, “The Delegation Model”. The concept behind it is fairly simple; a source generates an event and sends it to one or more listeners, the listener simply waits until it receives an event. Once an event is received, the listener processes the event and then returns.
In the above explanation there are 3 terms that you must be very clear on: Event, Source and Listener. They are discussed below:
Event: An event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface.
Source: A source is an object that generates an event. This occurs when the internal state of that object changes in some way. A source must register listeners in order for the listeners to receive notifications about a specific type of event.
Listener: A listener is an object that is notified when an event occurs. It has two major requirements:
- It must have been registered with one or more sources to receive notifications about specific types of events .
- It must implements methods to receive and process these notifications.
These are the basic terminologies of the event handling in Java. Make yourself familiar with it and be clear on the concept of the delegation model. It is important that you understand this so that you can have a firm rein on Java’s Event Handler.
Since we are done with the basics we now get into the nitty-gritty of Event Handling. All events in Java have a class representing them. Thus, a discussion of event handling must begin with the event classes. At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all events. Its one constructor is shown here:
EventObject(Object src)
Here src is the object that generates the event.
EventObject contains two methods: getSource() and toString(). The getSource() method returns the source of the event. Its general form is shown here:
Object getSource()
As expected the toString() returns the string equivalent of the event.
Below is a list of main event classes in Java along with a brief description.
| Event Class | Description |
| ActionEvent | Generated when a button is pressed, a list item is double-clicked, or a menu item is selected |
| AdjustmentEvent | Generated when a scroll bar is manipulated. |
| ComponentEvent | Generated when a component is hidden, moved, resized, or becomes visible. |
| InputEvent | Abstract superclass for all component input event classes. |
| ItemEvent | Generated when a check box or list item is clicked; also occurs when a choice selection is made or a checkable menu item is selected or deselected |
| KeyEvent | Generated when input is received from the keyboard. |
| MouseEvent | Generated when the mouse is dragged, moved, clicked, pressed, or released; also generated when the mouse enters or exits a component. |
| MouseWheelEvent | Generated when the mouse wheel is moved. |
| TextEvent | Generated when the value of the text area or text field is changed. |
| WindowEvent | Generated when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit. |
It is pretty obvious to see what would generate the events described above. But for the sake of it below is a list of sources that can generate the events described above.
| Event Source | Description |
| Button | Generates action events when the button is pressed. |
| Check Box | Generates itemevents when the check box is selected or deselected. |
| Choice | Generates item events when the choice is changed. |
| List | Generates action events when an item is double clicked; generates item events when an item is selected or deselected. |
| Menu Item | Generates action events when a menu item is selected; generates item events when a checkable menu item is selected or deselected. |
| Scroll Bar | Generates adjustment events when the scroll bar is manipulated. |
| Text Components | Generates text events when the user enters a character. |
| Window | Generates window events when a window is activated, closed, deactivated, deiconified, iconified, opened, orquit. |
As I explained above the Delegation Model has two parts: a source and a listener. Listeners are created by implementing one or more of the interfaces defined by the java.awt.event package. When an event occurs, the event source invokes the appropriate method defined by the listener and provides an event object as its argument. Below is a list of commonly used event listener interfaces:
| Interface | Description |
| ActionListener | Defines one method to receive action events. |
| AdjustmentListener | Defines one method to receive adjustment events. |
| ComponentListener | Defines four methods to recognize when a component is hidden, moved, resized, or shown. |
| ContainerListener | Defines two mthods to recognize when a component is added to or removed from a container. |
| FocusListener | Defines two methods to recognize when a component gains or loses keyboard focus |
| ItemListener | Defines one ethod to recognize when the state of an item changes. |
| KeyListener | Defines three methods to recognize when a key is pressed, released,, or typed. |
| MouseListener | Defines five methods to recognize when the mouse is clicked, enters a component, exits a component, is pressed or is released. |
| MouseMotion Listener | Defines two methods to recognize when the mouse is dragged or moved. |
| MouseWheelListener | Defines one method to recognize when the mouse wheel is moved. |
| TextListener | Defines one mthod to recognize when a text value changes. |
| WindowFocusLIstener | Defines two methods to recognize when a window gains or losses input focus. |
| WindowListener | Defines seven methods to recognize when a window is activated closed, deactivated, deiconified, iconified, opened, or quit. |
Now that we are done with the theoretical part, let’s get down to the implementation. To create the GUI, I will be using the same code that I had written in my previous stone on creating GUIs. I will show you how to use Java’s event handler by taking a sample ActionEvent whose source is a button, which is registered with an ActionListener. Note that I use the ActionEvent here, but the implementation of the other events and listeners described above, is pretty much the same. Here is the code for it:
package firstframe;
import javax.swing.*;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
public class frame implements ActionListener {
JFrame Frame1 = new JFrame("Test Frame");
JPanel j2 = new JPanel();
JButton b1 = new JButton ("Click me");
JTextField t1 = new JTextField(20);
JPanel j1 = new JPanel (new FlowLayout());
JLabel l1 = new JLabel("Name here: ");
public frame()
{
b1.addActionListener(this);
j1.add(l1);
j1.add(t1);
j2.add(b1);
Frame1.add(j1);
Frame1.add(j2);
Frame1.setLayout(new FlowLayout());
Frame1.setSize(400,150);
Frame1.setVisible(true);
Frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public void actionPerformed(ActionEvent e){
if (e.getSource() == b1){
t1.setText("Event Handling Done");
}
}
The code is pretty much self-explanatory, as I described above you need to first implement the interface ActionListener which is done by the bit of code below. Note that you will first need to import java.awt.event.* to be able to implement this interface.
import java.awt.event.*;
public class frame implements ActionListener {
Then you need to register the source , in our case here, the button with the listener.
b1.addActionListener(this);
And now you finally override the method actionPerformed method in the interface ActionListener to make the button do something.
public void actionPerformed(ActionEvent e){
if (e.getSource() == b1){
t1.setText("Event Handling Done");
}
The output of the above results in the text of the textfield t1 being set to, “Event Handling Done” when the button is pressed. A screen-shot of the output is given below
And with this we come to the end of event handling as well as the end of this part 2 of this tutorial on how to create effective GUIs. Watch this space for more on Java.
Subscribe to fortystones.
Follow @fortystones on Twitter.
Get updated from our Facebook Fanpage.
Related Posts
2 Comments + Add Comment
Leave a comment
Fortystones Lab Projects
Categories
- Articles (43)
- Idea (2)
- Review (5)
- Social Media (29)
- Trending Topics (13)
- Collection (29)
- How To (27)
- Linux (26)
- News (15)
- PHP (6)
- Project (1)
- Tutorials (35)
- Java (4)
- Programming (10)
- Wordpress (7)
Popular Posts
- 40 Basic Linux Command-line Tips and Tricks
- Tips and Tricks for Facebook Chat (Save History/ Video Chat/ Send Files)
- The First on the World Wide Web
- 40 Linux Shell Commands for Beginners
- Online Coding Zones for Programmers
- Special: Facebook Smiley, Special Text Symbols and ASCII Arts
- 13 years of Google: 1997- Present

An article by Prerak Pradhan







Nice Article, I followed it from the first article you had. Just one thing though, Missing a closing brace after “Frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);”
and at the end.