Lab2: Event Handling
Most of the codes and activities source: Introduction to Programming Using Java, Sixth EditionEvents
A GUI program must be prepared to respond to various kinds of events that can happen at any unpredictable time. Below is examples of simple events that the user can create:-
MouseEvent
When the user presses one of the buttons on a mouse, moves the mouse, drag... -
KeyEvent
When the user presses a key on the keyboard, a KeyEvent is created. -
WindowEvent
If the window or the frame of your application is changed (opened, closed, activated, deactivated), WindowEvent is generated. ActionEvent
This indicates the events generated by the component like Button, Checkboxes etc.
Event Listening
Listening to an event means some object(s) in our program detect the event and knows how to react to it. Depending on the type of the event that this object(s) are handling, they must contain instance methods that are specified in particular interfaces. Below is the list of interfaces that you might need for handling the above four types of eventsMouseListener
Listens for mouse clicks, mouse presses, mouse releases and mouse movement into or out of the component's drawing area.MouseMotionListeners
Listens for mous dragges, and mouse moveskeyListener
Listens for key presses.ActionListener
Listens for when the user clicks a button, chooses a menu item, presses Enter in a text fieldWindowListener
Listens for window events such as opening a window, closing a window, activating a window...
- The class must be declared to implement the interface, as in "class XYZHandler implements MouseListener".
- The class must include a definition for each instance method specified in the interface. (This is a general rule in Java for whenever you want to use an interface)
import java.awt.event.*;
public class xyz implements MouseListener {
public void mousePressed(MouseEvent evt){}
public void mouseReleased(MouseEvent evt){}
public void mouseClicked(MouseEvent evt){}
public void mouseEntered(MouseEvent evt)}
public void mouseExited(MouseEvent evt){}
}
Now depending of what the class wants to handle, it might impelemet
one or more of the specified methods in the inreface that it
implements.
For example:
import java.awt.event.*;
public class xyz implements MouseListener {
public void mousePressed(MouseEvent evt){
System.out.println("Mouse is pressed!!!!"):
}
public void mouseReleased(MouseEvent evt){}
public void mouseClicked(MouseEvent evt){}
public void mouseEntered(MouseEvent evt){}
public void mouseExited(MouseEvent evt){}
}
Activity 1
Write a class that implements WindowListener interface (complete WindowHandler nested class in the code below). Put all the nessasary methods inside your class. Implement the body of all of them with simple methods such as printing some sentences when this action accures so that you can test the different behaviours of a window. Save the class for the next activity.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainApplication{
private static class WindowHandler ...{
}
public static void main(String[] args) {
}
}
Hint: You could use Javadoc to find
which methods you need to include in your classes.
Or
You could use Eclipse to put all these methods for you! Once you said implement ..., then there is an error. You can go on the error and it will put all the methods for you!!
Event Registering
The last step in event handling is to register the listener object with the component(such as buttons,etc...) that produces the event (and you want your listener "hear"s that event)xyz mylistener = new xyz(); // Create MouseListener object. myButton.addMouseListener(mylistener);
Program Design Decision
When creating the event-listening objects, you have some options: The event-listener class could be a seperate class (or even a nested class), or you can choose that your main program handles these events. Lets say we want to print "Mouse is pressed!" whenever the user press the mouse inside our panel. The fllowing options demonstrate some code design decisions:-
The first code structure uses a seperaet class for handling the mouse
event. This pattern seperates the mouse handling functionality from
the rest of the code.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MainApp { public static void main(String[] args) { JFrame window = new JFrame("Random Strings"); JPanel content = new JPanel(); mouseHandler myMouseHandler=new mouseHandler(); content.addMouseListener( myMouseHandler ); // Register mouse listener. window.setContentPane(content); } private static class mouseHandler implements MouseListener { public void mousePressed(MouseEvent evt) { System.out.println("Mouse is pressed!"); } public void mouseClicked(MouseEvent evt) { } public void mouseReleased(MouseEvent evt) { } public void mouseEntered(MouseEvent evt) { } public void mouseExited(MouseEvent evt) { } } } - The following code implements the mouse listening behaviour in
the main application:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MainApp implements MouseListener { public static void main(String[] args) { JFrame window = new JFrame("Random Strings"); JPanel content = new JPanel(); MainApp myMainApp = new MainApp();//an object of the MainApp class handles events content.addMouseListener( myMainApp ); // Register mouse listener. window.setContentPane(content); } public void mousePressed(MouseEvent evt) { System.out.println("Mouse is pressed!"); } public void mouseClicked(MouseEvent evt) { } public void mouseReleased(MouseEvent evt) { } public void mouseEntered(MouseEvent evt) { } public void mouseExited(MouseEvent evt) { } } } -
The third patterns is similar to the second one, but here the main
function is used to create an instance of the class. The event
registering happens whenever a new object of the class is created
(inside class construction)
import java.awt.event.*; import javax.swing.*; public class MainApp implements MouseListener { public MainApp(){ JFrame window = new JFrame("Random Strings"); JPanel content = new JPanel(); content.addMouseListener( this ); // Register mouse listener. window.setContentPane(content); window.setVisible(true); } public static void main(String[] args) { MainApp myMainApp=new MainApp (); } public void mousePressed(MouseEvent evt) { System.out.println("Mouse is pressed!"); } public void mouseClicked(MouseEvent evt) { } public void mouseReleased(MouseEvent evt) { } public void mouseEntered(MouseEvent evt) { } public void mouseExited(MouseEvent evt) { } }
Activity2
Make sure that you understand the above codes and patterns. (And why they are correct)Activity3
Write a program that could compute and display the sum of a set of numbers entered by the user.- The panel should include a JTextField where the user enters a number. Beside your JTextField there is a text says: "Enter a new Number";
- The user can enter a new number and press "Enter" button.
- It should have another label that display the sum for the numbers that have been entered. Every time the user enters a new number, the sum displayed on the labels should change.
- There should be a "Reset" button that clears out all the data.
- When the user press the mouse inside your frame, all the text colors in your application set to a random color.
- When the user presses the exit icon on the main window, the program be closed and it will open a new window says "GoodBye!";
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainApplication implements MouseListener, ActionListener{
public MainApplication(){
// your constructor
}
private static class WindowHandler implements WindowListener{
// use activity 1 class here
}
public static void main(String[] args) {
MainApplication() myApplication= new MainApplication();
}
}
Hints: -
This program handles the actionListener for both of the buttons inside
just one method.
You can understand which buttons is pushed by useing the events that
it created.
event.getSource()
- To understand the Listeners that Swing Components Support go to: Listeners For example: an object handles Window Listener can just be added to a Dialog or a Frame.