event

Mouse button detection

With this example we shall show you how to use a MouseAdapter in order to detect which button of the mouse the user used. This is very useful when you want to add some extra functionality or flexibility to your application. It might be useful to the user to give input to the program using his mouse. Additionally you can make your application to behave differently according to which mouse button the user pressed.

In short, to find out what mouse button the user pressed you have to:

  • Create a class that extends MouseAdapter
  • Override mouseClicked to customize the handling of that specific event. Now every time the user clicks a button on his mouse, this method will be executed.
  • Use MouseEvent.getModifiers method and InputEvent class in order to find out which button was clicked.
  • Use MouseEvent.getPoint to get the coordinates of the point that the mouse button was clicked.

Let’s take a look at the code:

package methodoverloading;

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

import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {
  public static void main(String[] argv) throws Exception {

    JTextField text = new JTextField();
    text.addMouseListener(new MouseButtonRecogn());
    JFrame f = new JFrame();

    f.add(text);

    f.setSize(800, 600);

    f.setVisible(true);

  }
}

class MouseButtonRecogn extends MouseAdapter {

  @Override
  public void mouseClicked(MouseEvent event) {

    if ((event.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {

System.out.println("Left click detected" + (event.getPoint()));
    }

    if ((event.getModifiers() & InputEvent.BUTTON3_MASK) != 0) {

System.out.println("Right click detected" + (event.getPoint()));
    }

    if ((event.getModifiers() & InputEvent.BUTTON2_MASK) != 0) {

System.out.println("Middle click detected" + (event.getPoint()));
    }
  }
}

 
This was an example on how to perform mouse button detection.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron 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.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Julian
Julian
4 years ago

Instead of pulling up a window to click on, I would like to register clicks anywhere on screen. Any ideas?

Back to top button