Create Software Components 

Using Java Level 2

 

 

Course Info

Scheme

Resources

Tutorials

Java Demos

Utilities

Links


 

   Lecture 11

Event Handling

How do you handle events in Java so that your user interfaces respond to user actions such as the clicking of a button or the moving of a mouse?  So far all your applications have been written without any event handling functionality.  Now its time to learn about event types, event listeners and event handling methods.

Introduction

Event Handling Examples

Action Event Example

Mouse Event Example


Introduction

What are events?  When a user interacts with a graphical user interface they will expect the application to respond in some way to their actions.   Actions may be the clicking of a button, the selecting of an option, keyboard input etc.  Such user interaction generates events.

The applet shown below responds to a user clicking on the button.

~~~Applet~~~

To handle events in Java you need to do three things:-

  1. specify a class that will act as an event listener object.

  2. register the event listener object so it will  listen for events occurring to one or more components in your GUI.

  3. write the event handling code inside event handling methods

Let's get started.


Event Handling Examples

The three thing specified above will appear difficult at first.  So, before going into lengthy details about event listeners etc. and making it seem horribly complicated, let's first write some code with event handling capabilities.  This will give a very general idea of what you have to do.  We will go into the details in later sections

 


ActionEvent Example

An ActionEvent occurs when a user clicks a button or presses the enter key when the mouse cursor is inside a text field.  Let's have a look at code that handles ActionEvents.

Copy, compile and run the following code.  

Take note of the lines highlighted in bold.  These lines are important since they enable event handling functionality.  You should end up with an applet like the one shown above.

 

import java.awt.*;
import javax.swing.*;

import java.awt.event.*;
import javax.swing.event.*;

public class EventDemo extends JApplet implements ActionListener {

  public void init() {
     // set the layout to FlowLayout
    getContentPane().setLayout( new FlowLayout() );

     // create a button
    JButton button1 = new JButton ("Click Me");

     // register an event listener on the button
    button1.addActionListener(this);

     // add the buttons to the applet's content pane
    getContentPane().add(button1);
  }

     // method for handling Action Events
  public void actionPerformed (ActionEvent e) {

    JOptionPane.showMessageDialog (this, "You clicked a button!");

  }
}

 

~~Declare your class as an ActionListener~~

To give you a rough idea of what is going on, examine at the terms shown in bold below.

public class EventDemo extends JApplet implements ActionListener {

This specifies that the EventDemo class is going to implement the ActionListener interface class.  What does this mean?  Well, we know that an instance of a class is an object.  We create instances of classes all the time when we run our programs.  By specifying the EventDemo class as implementing ActionListener we are saying that the EventDemo class is also going to be an ActionListener object as well as an ordinary object and listen for action events.  

 

~~Implement the actionPerformed method of the ActionListener class~~

Now, any class that wants to become an ActionListener must deal with action events by implementing an actionPerformed method.  What that means in plain language is that the EventDemo class must write event handling code inside an actionPerformed method:-

  public void actionPerformed (ActionEvent e) {

    JOptionPane.showMessageDialog (this, "You clicked a button!");

  }

The ActionListener interface class has an actionPerformed method but it looks like this:-

  

There is no code inside the actionPerformed method.  If you like, you can think of the ActionListener interface as an unfinished class which needs to be finished off by another class, in this case the EventDemo class.  So by saying we are going to implement the ActionListener interface class, we are sort of making a deal ...  

The deal is that by becoming an ActionListener, a class must write any event handling code inside an actionPerformed method.  

 

~~Register an ActionListener on a component(s)~~ 

Now add the following code to your EventDemo class in the init() method.  Don't forget to recompile your code.

     // create another button
    JButton button2 = new JButton ("Click me too!");

     // add the buttons to the applet's content pane
    getContenPane().add(button2);

What happens when you click the second button?  Nothing right.  Try adding this line somewhere after your button creation line:-

     // register an event listener on the button
    button2.addActionListener(this);

Recompile and test your code.  You should now have two buttons that bring up a message box when clicked.  

So, the line...

button2.addActionListener(this)

...is important.  Without it nothing happens when you click the button. 

The addActionListener method registers an ActionListener on the button.  This means that you are informing Java that you wish for events occurring to the button to be noticed by an ActionListener.  The term in the parentheses (this) specifies that the ActionListener object that will listen for events occurring to this button is an instance of the class.  

The term this is a way for an object to refer to itself.

 

So, to handle ActionEvents you must...

  1. Declare your class as an ActionListener

  2. Write any event handling code inside an actionPerformed method.

  3. Register your ActionListener on one or more components using the addActionListener method

 

 


MouseEvent Example

Many components can react to mouse events.  The applet below demonstrates five types of mouse events -  mouse entered, mouse pressed, mouse clicked, and mouse exited..  

~~~Applet~~~

Copy, compile and run the following code.  

Take not of the lines highlighted in bold.  These lines are important since they enable event handling functionality.  You should end up with an applet similar the one shown above but without the image.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MouseEvents extends JApplet implements MouseListener{

  // declare an instance variable that will reference a label

  JLabel aLabel; 

  public void init() {

     // create a label
    aLabel = new JLabel("Mouse Event Demo!",JLabel.CENTER);

     // add a mouse listener to the label
    aLabel.addMouseListener(this);

     // add the label to the panel
    getContentPane().add(aLabel,BorderLayout.CENTER);

  }

  public void mouseClicked (MouseEvent e) {
    aLabel.setText(" Mouse Click ");
  }
  public void mouseEntered (MouseEvent e) {
    aLabel.setText(" Mouse Entered ");
  }
  public void mouseExited (MouseEvent e) {
    aLabel.setText(" Mouse Exited ");
  }
  public void mousePressed (MouseEvent e) {
    aLabel.setText(" Mouse Pressed ");
  }
  public void mouseReleased (MouseEvent e) {
    aLabel.setText("Mouse Released");
  }
}

 

~~Declare your class as an MouseListener~~

To give you a rough idea of what is going on, examine at the terms shown in bold below.

public class MouseEvents extends JApplet implements MouseListener {

This specifies that the MouseEvents class is going to implement the MouseListener interface class.  What does this mean?  Well, we know that an instance of a class is an object.  We create instances of classes all the time when we run our programs.  By specifying the MouseEvents class as implementing MouseListener we are saying that the MouseEvents class is also going to be an MouseListener object as well as an ordinary object and listen for mouse events.  

 

~~Implement all the methods of the MouseListener class~~

Now, any class that wants to become an MouseListener must deal with mouse events by implementing all the mouse methods.  What that means in plain language is that the MouseEvents class must write event handling code inside the mouse methods:-

  public void mouseClicked (MouseEvent e) {
    //put code in here if you want to respond to mouse clicks
  }
  public void mouseEntered (MouseEvent e) {
    //put code in here if you want to respond to the entering

    // of the mouse pointer from a component
  }
  public void mouseExited (MouseEvent e) {
    //put code in here if you want to respond to the exiting

    // of the mouse pointer from a component
  }
  public void mousePressed (MouseEvent e) {
    //put code in here if you want to respond to a mouse

    // button being pressed
  }
  public void mouseReleased (MouseEvent e) {
    //put code in here if you want to respond to the releasing

    // of a mouse button
  }

Any class that wants to become a MouseListener must implement ALL five of the mouse event handling methods.  Confirm this for yourself.  Change your code above so one of the mouse event handling methods is commented out:-

  //public void mouseReleased (MouseEvent e) {
  //  aLabel.setText("Mouse Released");
  //}

What happens when you recompile your code?  You will get a compiler error message:-

 

~~Register a MouseListener on a component(s)~~ 

The line of code in the MouseEvents class...

    aLabel.addMouseListener(this);

...is important.  Without it nothing happens when you interact with the label. 

The addMouseListener method registers a MouseListener on the label.  This means that you are informing Java that you wish for events occurring to the label to be noticed by an MouseListener.  The term in the parentheses (this) specifies that the MouseListener object that will listen for events occurring to this label is an instance of the class the label belong to.  

The term this is a way for an object to refer to itself.

 

So, to handle MouseEvents you must...

  1. Declare your class as an MouseListener

  2. Write any event handling code inside an methods of the MouseListener class.

  3. Register your MouseListener on one or more components using the addMouseListener method

 


That is folks!!

Now try the Event Handling exercises

 

  Site Home 

Java Home   

  Forum  

Course Info

Welcome

Overview

Assessment

Qualification

Scheme of Work

Assignments

Resources

Information

Blackboard

Learning Center

Web Materials

Reading

Java Demos

Utilities

Links

Lecture Materials

Tutorials & Notes

Exercises

Activities

Quizzes

 

Site Home

Top

Unit Home

ADR 2002