Java Graphical User Interface With JFrame: MouseEvents, MouseListener and MouseMotionListener
What Will I Learn?
- The user will learn the concept of MouseEvents in Java programming.
- The user will learn the concept of MouseListener in Java programming.
- The user will learn the concept of MouseMotionListener in Java programming.
- The user will learn how to implement the concept of Mouse EventHandling and ActionListening in Java programming.
Requirements
- A fully functional computer system is required for this tutorial
- On the computer system, Java Development Kit (JDK) must be installed.
- Also the computer system must have Java IDE installed. Probably Eclipse.
Get JDK here
Get Eclipse IDE here
Difficulty
- Intermediate.
Tutorial Contents
Welcome to this tutorial guys. Trust you are enjoying me as this wouldn't be the first time we meet on Java programming tutoring. We have previously discussed about several key concepts in Java programming such as Drawing Graphics, JColor Chooser, FlowLayout, Event Handling and the rest. Today, we are going to look into something new and as great as the previously discussed ones which comprises of MouseEvents, MouseListener and MouseMotionListener. Interesting, right? Of course!
We know very well the functionality of that pointing device - mouse and how important it is when interacting with computer system. As a programmer, we will be building programs that involves the use of mouse in the future and so I want us to look into every aspect involving mouse - it's events and action listening in general. Grab a cup of coffee (or are you a tea type?), now relax and follow me as we embark on this.
MouseEvent Interface
MouseEvent are those interesting actions that are performed with the use of the computer pointing device, mouse when interacting with a program in a computer system. These events or better still actions that require the use of mouse such as pressing mouse button, releasing mouse button, clicking mouse button (pressed & released), cursor entering and cursor exiting are events (basically actions) that are taken with the use of mouse.
An interface that represents the actions that are taken place when the user interact with the mouse is called MouseEvent Interface.
There are several types of Mouse Events. They are classed into:
Simple Events: Which includes
mousedown(mouse pressed),mouseup(mouse released),mouseover(mouse moves over an element),mouseout(mouse moving out of an element area) and so on.Complex Events however includes
left-click,right-clickand ``double-click`.
These actions listed above are called MouseEvents.
MouseListener
Listeners are notified whenever an event (action) takes place. They await actions to be taken and according to the instructions given by the programmer, they react to the actions that take place.
When the mouse button is clicked, or when any other mouse events take place, MouseListener listens to the exact event that occurs and thereafter, EventHandling can then execute some certain codes that has been programmed to be executed.
MouseMotion
MouseMotion is what occurs whenever the user moves the pointing device or when he uses the mouse to move the onscreen cursor or drag certain elements.
MouseMotionListener
I have already explain what listeners in general do. Just like others, the MouseMotion Listener is invoked when the mouse wheel is moved or certain element is dragged.
As you should be expecting, we will be creating a program that implements these concepts explained above. This program will help us understand how Mouse Events work and how they can be implemented when building a massive application.
This program we intend to build will have multiple classes and it is my style to explain each line of code as we progress in building our program. This will ensure that we all catch up pretty quick and understand these concepts pretty well. (I actually love pretty things) Don't mind me. Let's get to it guys.
The first class will be the program's sub-class and I'm naming this class tee.java. My name you ask? Yes! You could use yours too. This class will house our components - everything we intend to use in the program.
Sub-class tee.java
Take a quick glance on this class below.
That looks pretty sweet. It is time we start writing our code. Let's go guys.
The first things we need to do is to import some classes from the Java Foundation Classes (JFC) which we are going to help us in using our components. See how we do that below.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
We want to import everything from the AWT class as we need this class for creating the Borderlayout, colors etc and we have just done that. The java.awt.event.*; will pretty much help us in using the MouseEventsand lastly we need some couple of things from the javax.swing.*. Do not worry, I will be explaining everything we do here. Just follow me.
Now, we are going to extend this tee class with Frame. This pretty much allow us to use the frame window as needed by the program.
public class tee extends JFrame{
And so we have what we had above.
Now, it is time we make two variables. I believe we all know what variable means in Java programming and if you don't, variable simply takes a value and datatype. It could be anything.
private JPanel panel;
private JLabel status;
The JPanel panel is going to be the area where you can click, drag your mouse and do other MouseEvents and so it is just going to be one big white box. The second variable JLabel status is going to be a status bar that tells us whatever event that is taking with the mouse. It's just going to hold some couple of string texts that are going to be displayed as we interact with the mouse.
Now we need to create a constructor for this class.
public tee(){
As you could have noticed, the constructor take the name tee which pretty much represents the name of this class - tee,java. So you just need to change this to whatever you named your class. It doesn't take any parameter - you know, constructors thing.
Let's set the title of our Frame window.
super("Mouse Events Handling");
This title is what shows at the top of our window.
The next thing we are going to do now is to create our components for the variables we already declared up there; JPanel panel and JLabel status.
panel = new JPanel();
panel.setBackground(Color.WHITE);
add(panel, BorderLayout.CENTER);
status = new JLabel("Default");
add(status, BorderLayout.SOUTH);
I already mentioned what these components are and what we are going to use them for. The panel being where our mouse activities are going to take place is given the initial background color of WHITEand is centralised with respect to the frame window. The status label has an initial String "Default" being the default text String to be displayed.
In order to use the MouseEvents and MouseMotionEvents, we need to make a handler class. Later in this program, we are going to make a class which I intend to name handler and we are going to name it's object as h.
Let's first declare the class right here. See how we do that below.
handler h = new handler();
That is it about declaring the handler class.
Now we need to add two listeners as we are going to be implementing from two different classes of mouse events. Like I have made mention already in this tutorial, there are two types of mouse events - one being for the events that can take place when the mouse is still (pressed, clicked and released) and the other being for events that can be done while the mouse is moving (ie dragging).
panel.addMouseListener(h);
panel.addMouseMotionListener(h);
Above are the two listeners, taking the object of our handler class; h.
The next thing we are going to do now is to create our handler class but right before we do that, there is something I need us to make right before closing the tee.java constructor. We are going to set the setSize for our frame window and also make it visible. Let's do that now.
setSize(550,300);
setVisible(true);
We have set the setSize with 550 being the frame width and 300 being the frame set height.
Okay guys, let us create the handler class now. We are going to make this class private and make it implement the MouseListener and MouseMotionListener.
private class handler implements MouseListener, MouseMotionListener{
This pretty much allow us to use all the methods in the above classes; MouseListener and MouseMotionListener and with this, the program automatically detects the mouse events.
Now let's go ahead and build the methods in those classes and then we can see what happens.
The first thing we want to do is to build a method for mouseClicked event. MouseClicked is what happens when you press the mouse button and immediately release it. It's of course different from mousePressed. Let's do that now.
public void mouseClicked(MouseEvent e){
status.setText(String.format("Clicked at %d, %d", e.getX(), e.getY()));
}
The mouseClicked method takes MouseEvent e as its parameter and when this even occur, the JLabel status is set to display some String of texts. To make this interesting, I added String.format which is used to format the string that will be displayed. The String.format takes three parameters; the first being the String text to be displayed "Clicked at %d, %d" where the %d, %d represents the area being clicked at coordinates X and Y respectively, with these two coordinates being the other two parameters.
That looks kind of complicated? Do not worry guys, it is going to get easier as we proceed. Let's go ahead and create the methods for the other mouse events.
Now we are going to make methods for mousePressed, mouseReleased, mouseEntered and mouseExited. Just like you I believe you understand because these look original, these methods will implement what happens when the mouse is pressed(pressed and hold for a while), released, when the mouse pointer enters the panel area and when the pointer exits the panel area.
public void mousePressed(MouseEvent e){
status.setText("You pressed down the mouse");
}
public void mouseReleased(MouseEvent e){
status.setText("You released the mouse button");
}
public void mouseEntered(MouseEvent e){
status.setText("You have entered the window area");
panel.setBackground(Color.BLUE);
}
public void mouseExited(MouseEvent e){
status.setText("You have left the window area");
panel.setBackground(Color.RED);
}
Those methods look simpler compared to what we did on the mouseClicked, right? You remember I promised they would. The strings that we made on the status label are what the JLabel status displays when each of the respective event occurs. The only difference is that we set certain background colors to the JPanel panel. When the mouse is hovered or better still enters the panel area, the background color turns BLUE, and as it exits the area, the background color changes to RED. That looks creative you say... After all coding is creative. Let's move on guys.
We are through with implementing the MouseListener and it is time we move into implementing the MouseMotionListener.
Let's start with building the mouseDragged method. This implements what happens when the user drag the mouse on the JPanle panel placed on the frame window.
public void mouseDragged(MouseEvent e){
status.setText("You are dragging the mouse");
}
public void mouseMoved(MouseEvent e){
status.setText("You moved the mouse");
}
The difference between the mouseDragged and mouseMoved is that with mouseDragged, the user click the mouse button and then moves it while with mouseMoved, the user only moves the mouse without clicking the mouse button. The JLabel status displays "You are dragging the mouse" when the mouse is dragged and "You moved the mouse" when the user only moves the mouse.
That is all for the sub-class tee.java. See the full code for tee.java class below.
tee.java Full Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class tee extends JFrame{
private JPanel panel;
private JLabel status;
public tee(){
super("Mouse Events Handling");
panel = new JPanel();
panel.setBackground(Color.WHITE);
add(panel, BorderLayout.CENTER);
status = new JLabel("Default");
add(status, BorderLayout.SOUTH);
handler h = new handler();
panel.addMouseListener(h);
panel.addMouseMotionListener(h);
setSize(550,300);
setVisible(true);
}
private class handler implements MouseListener, MouseMotionListener{
public void mouseClicked(MouseEvent e){
status.setText(String.format("Clicked at %d, %d", e.getX(), e.getY()));
}
public void mousePressed(MouseEvent e){
status.setText("You pressed down the mouse");
}
public void mouseReleased(MouseEvent e){
status.setText("You released the mouse button");
}
public void mouseEntered(MouseEvent e){
status.setText("You have entered the window area");
panel.setBackground(Color.BLUE);
}
public void mouseExited(MouseEvent e){
status.setText("You have left the window area");
panel.setBackground(Color.RED);
}
public void mouseDragged(MouseEvent e){
status.setText("You are dragging the mouse");
}
public void mouseMoved(MouseEvent e){
status.setText("You moved the mouse");
}
}
}
The execution of Java programs is the responsibility of the main class. The main class has the main method in it. Of course you can choose to use a single super class for your whole program and add the main method class within the single class. However, it is good to understand how to use multiple classes within your program as this is very ideal when building a very big program.
It is time we make the main class for our program.
Main class king.java
Take a quick look at this class below.
Like I said, this is responsible for executing our program. Let's start with it.
Firstly, we are going to import the swing.JFrame from the javax class.
import javax.swing.JFrame;
This pretty much allows us to use the frame window for this program.
We must not forget to include the main method which helps in execution of this program. Let's do that now.
public static void main(String[] args) {
Now it is time we call in the sub-class tee.java in here. This will link the two classes; the main calss and the sub-class together.
tee t = new tee();
Remember tee is the name of the sub-classwhilet`` is just an object. You can name it whatever you like, just make sure that the sub-class name is not mistaken here.
Now there is only one thing to round this program. In java programming, you need to make the termination process for your program. This will enable the user to be able to close the program. See how we do that below.
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
With that, the program can be terminated after use.
Se the full code for our program's sub-class below.
king.java Full Code
import javax.swing.JFrame;
public class king {
public static void main(String[] args) {
tee t = new tee();
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Now that we are through with building our program, it is time we run the program to see how it works.
Output
As the program is launched, the default background for the panel is set as
WHITE and the status displays "Default`` just as we programmed it.
As the mouse is moved into the panel area, the background color turns
BLUE with the status label saying "You have entered the window area".
As the mouse is moved away from the panel area, the background color turns
RED with the status label saying "You have left the window area".
When the mouse is moved on the panel area, the status says "You moved the mouse".
When you press the mouse button, the status says "You pressed down the mouse".
When you click the mouse button, the status says "Clicked at" with the coordinates on the X and Y axis.
This tutorial has covered vast areas of the mouse events, very vital concepts in programming.
Source Code On GitHub
The source code for this program is available on my GitHub. You can check it out.
Curriculum
- Java Graphical User Interface With JFrame: FlowLayout With Eclipse
- Java Graphical User Interface With JFrame: JColorChooser With Eclipse
- Java Graphical User Interface With JFrame: Drawing Graphics With Eclipse
- Java Graphical User Interface With JFrame: Event Handling And Action Listening
Posted on Utopian.io - Rewarding Open Source Contributors
Hello! I find your post valuable for the wafrica community! Thanks for the great post! @wafrica is now following you! ALWAYs follow @wafrica and use the wafrica tag!
Your contribution cannot be approved because it does not follow the Utopian Rules.
You can contact us on Discord.
[utopian-moderator]