awt
Handling Mouse Clicks
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
MouseListener
and add it to the JFrame - Use
MouseEvent.getModifiers()
and InputEvent masks to see what button of the mouse the user clicked - Use
MouseEvent.getPoint()
to get the coordinates of the point that the users clicked into.
So, let’s see the code snippet bellow:
package com.javacodegeeks.snippets.desktop; 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 HandlingMouseClicks { public static void main(String[] argv) throws Exception { // Create a new JFrame window JTextField compnt = new JTextField(); compnt.addMouseListener(new MouseListener()); JFrame frame = new JFrame(); frame.add(compnt); frame.setSize(800, 800); frame.setVisible(true); } } class MouseListener extends MouseAdapter { public void mouseClicked(MouseEvent event) { if ((event.getModifiers() & InputEvent.BUTTON1_MASK) != 0) { System.out.println("left" + (event.getPoint())); } if ((event.getModifiers() & InputEvent.BUTTON2_MASK) != 0) { System.out.println("middle" + (event.getPoint())); } if ((event.getModifiers() & InputEvent.BUTTON3_MASK) != 0) { System.out.println("right" + (event.getPoint())); } } }
Output:
leftjava.awt.Point[x=556,y=253] leftjava.awt.Point[x=512,y=394] leftjava.awt.Point[x=512,y=394]
This was an example on how to handle mouse clicks in Java.