JFrame
Create JFrame window with mouse event handling
This is an example that demonstrates how to create a JFrame
windows that supports mouse event handling. This is very useful in most GUI applications because most of the time it is very efficient for the user to provide input using his mouse. Additionally, you can make your application behave accordingly to mouse movement and generally to mouse events.
Basically all you have to do in order to create a JFrame
that handles mouse events is:
- Create a class that extends
JFrame
and implementsMouseListener
. - Overrde
mouseClicked
,mouseEntered
,mouseExited
,mousePressed
,mouseReleased
to monitor the coresponding events. Now every time one of these events occures, the respective function will fire up. - Use
MouseEvent.getX()
,MouseEvent.getY()
to get the coordinates of the window that the mouse event occurs.
Let’s see the code:
package com.javacodegeeks.snippets.desktop; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; public class CreateJFrameWindowWithMouseEventHandling extends JFrame implements MouseListener { private static final long serialVersionUID = 1L; public CreateJFrameWindowWithMouseEventHandling() { setTitle("Simple Frame"); addMouseListener(this); } @Override public void mouseClicked(MouseEvent e) { int x = e.getX(); int y = e.getY(); System.out.println("Mouse Clicked at X: " + x + " - Y: " + y); } @Override public void mouseEntered(MouseEvent e) { int x = e.getX(); int y = e.getY(); System.out.println("Mouse Entered frame at X: " + x + " - Y: " + y); } @Override public void mouseExited(MouseEvent e) { int x = e.getX(); int y = e.getY(); System.out.println("Mouse Exited frame at X: " + x + " - Y: " + y); } @Override public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); System.out.println("Mouse Pressed at X: " + x + " - Y: " + y); } @Override public void mouseReleased(MouseEvent e) { int x = e.getX(); int y = e.getY(); System.out.println("Mouse Released at X: " + x + " - Y: " + y); } private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new CreateJFrameWindowWithMouseEventHandling(); //Display the window. frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
This was an example on how to create JFrame window with mouse event handling.
Tested, it works fine. Thank you!