event
Handle 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 theJFrame
usingaddMouseListener
method. - Use
MouseEvent.getModifiers()
andInputEvent
orMouseEvent
masks to see what button of the mouse the user clicked. Alternatively you can useMouseEvent.getButton()
method - Use
MouseEvent.getX()
andMouseEvent.getY()
to get the coordinates of the point that the user clicked into. - Alternatively you can use
MouseEvent.getPoint().x
andMouseEvent.getPoint().y
to get the coordinates. - 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.BorderLayout; import java.awt.Component; import java.awt.Frame; import java.awt.TextArea; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class MouseListener { public static void main(String[] args) { // Create frame with specific title Frame frame = new Frame("Example Frame"); // Create a component to add to the frame; in this case a text area with sample text Component textArea = new TextArea("Click here to see mouse click info..."); // Add a mouse listener to capture click events textArea.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { TextArea source = (TextArea) evt.getSource(); if ((evt.getModifiers() & InputEvent.BUTTON1_MASK) != 0) { source.setText(source.getText() + "nLeft mouse button clicked on point [" + evt.getPoint().x + "," + evt.getPoint().y + "]"); } if ((evt.getModifiers() & InputEvent.BUTTON2_MASK) != 0) { source.setText(source.getText() + "nCenter mouse button clicked on point [" + evt.getPoint().x + "," + evt.getPoint().y + "]"); } if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) != 0) { source.setText(source.getText() + "nRight mouse button clicked on point [" + evt.getPoint().x + "," + evt.getPoint().y + "]"); } } }); // Add the components to the frame; by default, the frame has a border layout frame.add(textArea, BorderLayout.NORTH); // Show the frame int width = 300; int height = 300; frame.setSize(width, height); frame.setVisible(true); } }
This was an example on how to handle mouse clicks in Java.