Java Graphical User Interface(GUI): Mouse Events and Listeners Using Eclipse IDE

in #utopian-io7 years ago (edited)

What Will I Learn?

  • The user will learn the concept of MouseListener
  • The user will learn the concept of MouseMotionListener
  • The user will learn how to associate MouseListener methods with actions.
  • The user will learn how to associate MouseMotionListener methods with actions.

Requirements

  • A computer System is required for this tutorial.
  • Java Software Development Kit(JDK) must be installed on your computer.
  • An Integrated Development Environment(IDE) such as Eclipse or NetBeans is required to be installed on your computer.

Get JDK here

Get Eclipse here

Get NetBeans here

Difficulty

The codes in this tutorial are around the same level as other tutorials so difficulty level will be same as others - Intermediate.

Tutorial Contents

Over time, we have looked at Swing components, and how to associate them with actions, we have also looked at actions associated with buttons and clicking of a button.

In this tutorial, we will look at events associated with Mouse, and actions that can be performed when an operation is done using the mouse or mouse button. We will create a panel, implement the five methods in MouseListener and the two methods in MouseMotionListener, using a status bar to inform us when a new event is registered and also change the background color of the panel.

Mouse Events and Listeners

The mouse is associated with numerous events. The mouse can perform various button either when moved or when clicked.
There are two major Listeners associated with Mouse Events

MouseListener

This is the listener interface for receiving "interesting" mouse events. The Java MouseListener is notified whenever you change the state of mouse. It is notified against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods.

public void mouseClicked(MouseEvent e);  
public void mouseEntered(MouseEvent e);  
public void mouseExited(MouseEvent e);  
public void mousePressed(MouseEvent e);  
public void mouseReleased(MouseEvent e);

The class that is interested in processing a mouse event either implements this interface (and all the methods it contains) or extends the abstract MouseAdapter class (overriding only the methods of interest).

The listener object created from that class is then registered with a component using the component's addMouseListener method. A mouse event is generated when the mouse is pressed, released clicked (pressed and released). A mouse event is also generated when the mouse cursor enters or leaves a component. When a mouse event occurs, the relevant method in the listener object is invoked, and the MouseEvent is passed to it.

MouseMotionListener

This is the listener interface for receiving mouse motion events on a component. The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified against MouseEvent. The MouseMotionListener interface is found in java.awt.event package. It has two methods.

public void mouseDragged(MouseEvent e);  
public void mouseMoved(MouseEvent e);

The class that is interested in processing a mouse motion event either implements this interface (and all the methods it contains) or extends the abstract MouseMotionAdapter class (overriding only the methods of interest).

The listener object created from that class is then registered with a component using the component's addMouseMotionListener method. A mouse motion event is generated when the mouse is moved or dragged. (Many such events will be generated). When a mouse motion event occurs, the relevant method in the listener object is invoked, and the MouseEvent is passed to it.

8.png

9.png

10.png

CODE BLOCK

mouseEvents Class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class mouseEvents extends JFrame {
    private JPanel panel;
    private JLabel messageBar;
    public mouseEvents() {
        super("Mouse Events Demo");
        panel = new JPanel();
        panel.setBackground(Color.BLACK);
        add(panel, BorderLayout.CENTER);
        messageBar = new JLabel("Status");
        add(messageBar, BorderLayout.SOUTH);
        handlerClass mouseEvent = new handlerClass();
        panel.addMouseListener(mouseEvent);
        panel.addMouseMotionListener(mouseEvent);
    }
    private class handlerClass implements MouseListener, MouseMotionListener {
        public void mouseClicked(MouseEvent event) {
            messageBar.setText("Mouse button have been clicked");
        }
        public void mousePressed(MouseEvent event) {
            messageBar.setText("Mouse button have been pressed");
        }
        public void mouseReleased(MouseEvent event) {
            messageBar.setText("Mouse Button has been released");
        }
        public void mouseEntered(MouseEvent event) {
            panel.setBackground(Color.YELLOW);
            messageBar.setText("Mouse cursor has entered the panel.");
        }
        public void mouseExited(MouseEvent event) {
            panel.setBackground(Color.BLACK);
            messageBar.setText("Mouse cursor have exited the panel");
        }
        public void mouseDragged(MouseEvent event) {
            messageBar.setText("Mouse is being dragged");
        }
        public void mouseMoved(MouseEvent event) {
            messageBar.setText("Mouse is being moved");
        }
    }
}
mouseMain Class
import javax.swing.JFrame;
public class mouseMain {
    public static void main (String args []) {
        mouseEvents event = new mouseEvents();
        event.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        event.setSize(500, 300);
        event.setVisible(true);
    }
}

mouseEvents Class

panel = new JPanel();
panel.setBackground(Color.BLACK);
add(panel, BorderLayout.CENTER);

A JPanel object is created and background color is set to Black.
The panel is added to the screen, the

BorderLayout.CENTER

Method is used to place the panel in the center of the screen.

messageBar = new JLabel("Status");
add(messageBar, BorderLayout.SOUTH);

A JLabel object is created and added to the screen. This will be a status bar to inform the user when a mouse event has taken place. The status bar will be at the bottom of the panel. This is achieved by using SOUTH on the BORDERLAYOUT method.

private class handlerClass implements MouseListener, MouseMotionListener {

The two main listeners that mouse events implements from.

public void mouseClicked(MouseEvent event) {
            messageBar.setText("Mouse button have been clicked");
        }
        public void mousePressed(MouseEvent event) {
            messageBar.setText("Mouse button have been pressed");
        }
        public void mouseReleased(MouseEvent event) {
            messageBar.setText("Mouse Button has been released");
        }
        public void mouseEntered(MouseEvent event) {
            panel.setBackground(Color.YELLOW);
            messageBar.setText("Mouse cursor has entered the panel.");
        }
        public void mouseExited(MouseEvent event) {
            panel.setBackground(Color.BLACK);
            messageBar.setText("Mouse cursor have exited the panel");
        }
        public void mouseDragged(MouseEvent event) {
            messageBar.setText("Mouse is being dragged");
        }
        public void mouseMoved(MouseEvent event) {
            messageBar.setText("Mouse is being moved");
        }

These are the five methods contained in MouseListener class and two methods contained in the MouseMotionListener class.

MouseListener

The method mouseClicked simply means when the mouse is pressed and released immediately.

The method mousePressed means when the mouse is clicked and held.

The method mouseReleased means when the mouse is let go after it is pressed.

The method mouseEntered means when the mouse cursor enters the panel area.

The method mouseExited refers to when the mouse cursor exits the panel area.

MouseMotionListener

The method mouseDragged refers to when the mouse is pressed and dragged.

The method mouseMoved refers to when the mouse is moved within the panel area.

The status bar at the bottom of the panel displays a text message notifying the user of the current event each time a new event is registered.

The background color of the panel also changes to yellow and black each time the mouse cursor enters and exits the panel.

mouseMain CLASS

import javax.swing.JFrame;

This is an import statement. This statement is used specifically to import the JFrame class from Application Program Interface (API). This allows the user to use all methods contained in it.

public class mouseMain {

This is just like creating a new file or document and saving it with a name. This is the name of the new class created.

public static void main (String args []) {

The Java main method. Every program must contain this method in order to execute. It is the point from which the program begins execution.
A program without this method will not execute.

mouseEvents event = new mouseEvents();

An Object of the mouseEvents class is created. This enables the user to call in built GUI methods that will help to properly display the JPanel and JLabel components to the screen.

event.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

This inbuilt method needs to be called before the program is run . This method states the default behavior of the windows when the “close”(x) button is clicked.
Here, it tells the window to close.

event.setSize(500, 300);

This is to set the size of the object to the specified width and height. In this case, the specified dimensions are (500, 300).

Values of width and height are non-negative integers. The constructors that allow you to create a dimension do not prevent you from setting a negative value for these properties. If the value of width or height is negative, the behavior of some methods defined by other objects is undefined.

event.setVisible(true);

This simply determines whether a component is displayed on the screen. It has two states. True and false.

With setVisible( false ), if the Component is not already marked invisible, setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now more screen real estate in the Container and the positions of the siblings must be adjusted to flow into the freed space.

With setVisible( true ), if the Component is not already marked visible,setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now less screen real estate in the Container and the positions of the siblings must be adjusted to squeeze in this new Component.

1.png

The status Bar below displays a text when the mouse cursor enters the panel area and when the mouse is clicked. The background also changes when the cursor enters the panel area.

2.png

When the mouse is pressed and held, a message displays on the status bar.

3.png

When the mouse is released after being pressed, a message displays on the status bar.

4.png

When the mouse cursor enters the panel area, a message displays on the status bar and background color changes to yellow

5.png

When the mouse cursor exits the panel area, a message displays on the status bar and background color changes to black

6.png

When the mouse is pressed and dragged, a message displays on the status bar.

7.png

When the mouse is moved, a message displays on the status bar.

11.png

12.png

13.png

Source Codes from GitHub Account.

You can get the codes here if you want to try it on your own.

REFERENCES

Curriculum

Similar posts already posted on Utopian are:



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by will-ugo from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, theprophet0, someguy123, neoxian, followbtcnews, and netuoso. The goal is to help Steemit grow by supporting Minnows. Please find us at the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: 50SP, 100SP, 250SP, 500SP, 1000SP, 5000SP.
Be sure to leave at least 50SP undelegated on your account.

Hey @will-ugo I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x