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 andInputEvent
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.
Instead of pulling up a window to click on, I would like to register clicks anywhere on screen. Any ideas?