event

Handling Mouse Clicks example

In this short tutorial we are going to see how to monitor a very basic GUI event in Java Desktop Applications, which is mouse clicks. What we want to see is what button mouse the user pressed (left, middle or right click) and then we want to know the exact location, in coordinates, in our Frame that this event occurred.

In short, to handle mouse clicks in a Java AWT application :

  • Create a JFrame
  • Create a MouseAdapter and add it to the JFrame using addMouseListener method.
  • Use MouseEvent.getModifiers() and InputEvent or MouseEvent masks to see what button of the mouse the user clicked. Alternatively you can use MouseEvent.getButton() method
  • Use MouseEvent.getX() and MouseEvent.getY() to get the coordinates of the point that the user clicked into.
  • Use MouseEvent.getClickCount to get the amount of clicks that the user performed.
So, let’s see the code snippet bellow:
package com.javacodegeeks.snippets.desktop;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class Main extends JFrame {

    public Main() {

  setSize(600, 600);

  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  final JTextArea text = new JTextArea();

  text.setText("Click inside the white area. Use all the buttons in your mouse!");

  text.addMouseListener(new MouseAdapter() {

@Override

public void mouseClicked(MouseEvent event) {

    if (event.getButton() == MouseEvent.NOBUTTON) {

  text.setText("No button clicked");

    } else if (event.getButton() == MouseEvent.BUTTON1) {

  text.setText("Button 1 clicked");

    } else if (event.getButton() == MouseEvent.BUTTON2) {

  text.setText("Button 2 clicked");

    } else if (event.getButton() == MouseEvent.BUTTON3) {

  text.setText("Button 3 clicked");

    }

    System.out.println("Number of clicks: " + event.getClickCount());

    System.out.println("Pointing at (X, Y):  " + event.getX() + ", " + event.getY());

}

  });

  getContentPane().add(text);
    }

    public static void main(String[] args) {

  new Main().setVisible(true);
    }
}

 
This was an example on how to handle mouse clicks in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button