- Programming Examples
- Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here 🙂
- AWT MouseListener & MouseMotionListener
- 1. AWT MouseListener & MouseMotionListener
- 2. Mouse Buttons & AWT Button Constants
- 3. AWT MouseListener Events
- 4. AWT MouseMotionListener Events
- 5. Learn Mouse Press, Release, Click & Double-Click
- 6. About the MouseListener Example
- 7. Frame Window
- Dragging Java Components Using Mouse
- Java move components with mouse
- What is the right way to move the mouse in a game?
- Java: mouseDragged and moving around in a graphical interface
- Simulate mouse move and key pressing
Programming Examples
Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here 🙂
AWT MouseListener & MouseMotionListener
1. AWT MouseListener & MouseMotionListener
The MouseListener and MouseMotionListener are listener interfaces for picking up the mouse actions. MouseListener is to, track the mouse events–Enter, Exit, Press, Release and Click. MouseMotionListener is to capture the mouse move as well as mouse drag. Note, drag is nothing but moving the mouse with one of its buttons in pressed state. For example, to move a window from one area to other area on the desktop screen we end up in dragging the mouse with the left button pressed down on the window title.
In this example, we will explore both the listeners and how it captures the mouse events. Let us start Java AWT Mouse Example.
2. Mouse Buttons & AWT Button Constants
In 80s, usually mouse came with only two buttons. One is for left click and other one is for right click. Now as days mouse comes with three buttons and a wheel in the middle. The wheel allows scrolling the contents, and also it allows click. Below is the picture of the modern days mouse:
The above picture has three mouse buttons. Java AWT will identify these buttons with constants BUTTON1, BUTTON2 and BUTTON3. These constants are sequential from left to right. Means, in the picture we can map the buttons with Java AWT constants as follows:
- Mouse Button 1 => Left Mouse Button => BUTTON1
- Mouse Button 2 => Right Mouse Button => BUTTON3
- Mouse Button 3 => Middle Mouse Button => BUTTON2
Note, you can do a middle click by pressing and releasing the wheel. The wheel is multi purpose as you can do scroll and click.
3. AWT MouseListener Events
AWT MouseListener is useful to track the mouse events. Have a look at the below picture:
The MouseListener will watch for Six mouse events. They are:
- Mouse Pressed: The event is received when the user pressed any of the possible three mouse buttons.
- Mouse Released: When the user released the pressed mouse button, this event is thrown.
- Mouse Enter: The component registered with the listener will receive this event when mouse cursor enters it.
- Mouse Exit: When the cursor goes off the component, AWT reports this exit event.
- Mouse Clicked: When mouse is pressed and released at the same location (x & y), AWT will produce Mouse Clicked event.
Say for example, we want to track mouse enter and exit on the TextArea component. Then, to achieve it, we will register the TextArea component with the MouseListener. Now TextArea component will send the mouse events to the MouseListener handler function.
4. AWT MouseMotionListener Events
MouseMotionListener will look for the mouse move and mouse drag events. It captures the mouse path in terms of x and y coordinate values. Have a look at the below picture:
The picture shows how the MouseMotionListener tracks the mouse motion path. The event will be made at periotic interval quick enough to capture the motion path solidly. However, moving the mouse so fast will not produce enough events and listener will lose intermediate x & y values. Mouse Drag is same as Mouse Move with an exception that at least one button should in pressed state while mouse is moving. Mouse Drag is vital to carry out Drag & Drop feature.
5. Learn Mouse Press, Release, Click & Double-Click
Mouse Click is a combination of pressing a specific mouse button and releasing it. The double-click is a combination of two mouse clicks. Have a look at the below picture:
The top portion shows the click event of the mouse. Java AWT treats a mouse button press and release as a click when the press & release happens at the same coordinate location.
For a double click, the click events (two clicks) should happen within a specific time limit. In the above picture (bottom portion), the first two clicks happened for a long duration and hence they are treated as two separate mouse clicks. The next four clicks happened so quickly and hence AWT considered it as two Double-Click events. The above picture notes this as with two Green arrow marks. In windows OS, we can configure double-click time interval via control panel -> mouse settings.
6. About the MouseListener Example
Now we have basic information about the mouse events. The below picture shows the example we want to create:
AWT Frame Window houses a AWT Panel in the middle. This is the panel which will track the mouse events in our example. In the bottom of the Frame, we will have a AWT Label Control to report the mouse events. Now, let us proceed with the example.
7. Frame Window
In the program entry, we create an instance of the AWTMouseExample which we will derive from the Frame window. Next, we set this Frame Window visible to the users. Below is the code:
Dragging Java Components Using Mouse
Question: I attempted to enable drag-and-drop functionality for a Component through the use of mouse listeners and the function of [insert function name]. Solution 1: To achieve this, [insert subject] must be accompanied by the appropriate definitions in voids. However, if you are in need of a better solution, there is an excellent code available for ComponentMover. Solution 2:
Java move components with mouse
I attempted to enable drag functionality for various Components using mouse listeners and the setLocation function provided by java.awt.Component . As an initial test, I applied this approach to JButton .
Below is a sample code that exemplifies my objective.
import java.awt.*; import javax.swing.*; public class DragButton extends JButton < private volatile int draggedAtX, draggedAtY; public DragButton(String text)< super(text); setDoubleBuffered(false); setMargin(new Insets(0, 0, 0, 0)); setSize(25, 25); setPreferredSize(new Dimension(25, 25)); addMouseListener(new MouseAdapter()< public void mousePressed(MouseEvent e)< draggedAtX = e.getX() - getLocation().x; draggedAtY = e.getY() - getLocation().y; >>); addMouseMotionListener(new MouseMotionAdapter() < public void mouseDragged(MouseEvent e)< setLocation(e.getX() - draggedAtX, e.getY() - draggedAtY); >>); > public static void main(String[] args) < JFrame frame = new JFrame("DragButton"); frame.setLayout(null); frame.getContentPane().add(new DragButton("1")); frame.getContentPane().add(new DragButton("2")); frame.getContentPane().add(new DragButton("3")); frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); >>
I’m not sure why, but there seems to be an issue with this. When dragging the mouse, the distance traveled is only half of the actual mouse movement. Additionally, the distance flickers back and forth, as if two competing factors are at play. These factors may be related to the mouse positions and MouseMotionListener .
Could someone assist a beginner in swing/awt? =) I appreciate your help in advance.
The issue was that I was unaware that the event would trigger repeatedly at every mouse position, with the position being in relation to the triggering JComponent . As a result, I have made the necessary corrections to the code, and it is now functioning properly.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class DragButton extends JButton < private volatile int draggedAtX, draggedAtY; public DragButton(String text)< super(text); setDoubleBuffered(false); setMargin(new Insets(0, 0, 0, 0)); setSize(25, 25); setPreferredSize(new Dimension(25, 25)); addMouseListener(new MouseAdapter()< public void mousePressed(MouseEvent e)< draggedAtX = e.getX(); draggedAtY = e.getY(); >>); addMouseMotionListener(new MouseMotionAdapter() < public void mouseDragged(MouseEvent e)< setLocation(e.getX() - draggedAtX + getLocation().x, e.getY() - draggedAtY + getLocation().y); >>); > public static void main(String[] args) < JFrame frame = new JFrame("DragButton"); frame.setLayout(null); frame.getContentPane().add(new DragButton("1")); frame.getContentPane().add(new DragButton("2")); frame.getContentPane().add(new DragButton("3")); frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); >>
I appreciate Adel’s hard work and mKorbel for sharing the link.
You must utilize JComponent to ensure smooth movement. I long for the inclusion of mousePressed/mouseDragged in empty spaces. However, @[camickr][1] surpasses all other options as the superior code for ComponentMover.
import javax.swing.*; import java.awt.event.*; public class movingButton extends JFrame < private JButton button ; public movingButton () < super("Position helper"); super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); super.setSize(500,520); super.setVisible(true); super.setLayout(null); button = new JButton ("drag me "); add(button); button.setBounds(100, 100, 150, 40); button.addMouseMotionListener(new MouseAdapter()< public void mouseDragged(MouseEvent E) < int X=E.getX()+button.getX(); int Y=E.getY()+button.getY; button.setBounds(X,Y,150,40); >>); > public static void main (String x[]) < new movingButton(); >>
Have you considered implementing the Transferable interface in Java instead?
Check out this tutorial that provides step-by-step instructions on how to perform the task: http://www.javaworld.com/javaworld/jw-03-1999/jw-03-dragndrop.html
It is better if you would do
int X=E.getX() + button.getX(); int Y=E.getY() + button.getY();
Java — handle mouse move and click together in javafx, When the mouse is clicked and held, instead of onMouseMoved use onMouseDragged with same method signature. I believe that should satisfy your requirements. As for the exception, just for your information, in order to run code on JavaFX Application Thread simply call Platform.runLater (some Runnable code); …
What is the right way to move the mouse in a game?
My goal is to create a minecraft bot that gathers items without manual intervention. However, I’m struggling with mouse movement in the game. The mouse cursor moves erratically, jumping around at both the x and y coordinates, even with small adjustments to the y coordinate. This issue persists not just in minecraft but in all 3D games.
To execute the motion, the robot class that is integrated is utilized.
This is the code I utilize for controlling the movement of the mouse:
public static void main(String[] args) < try < Robot bot = new Robot(); Point mouseposition = MouseInfo.getPointerInfo().getLocation(); int x = mouseposition.x; int y = mouseposition.y; //used to switch to the game window bot.delay(5000); y += 1; bot.mouseMove(x, y); >catch (AWTException e) < // TODO Auto-generated catch block e.printStackTrace(); >>
My anticipation for this code was that the course would shift downwards by a single pixel. The cursor performs smoothly on the desktop.
Before switching to the game window, make sure to capture the mouse location. By doing this, when you increase the y coordinate by 1, you will be adding 1 to the mouse’s previous position, before it was moved to the game window. To achieve this, place the delay before the Point mouseposition = MouseInfo.getPointerInfo().getLocation(); line.
Java: Move image towards mouse position, 1 Answer. Sorted by: 5. The answer will depend on what you mean by «move towards» For example, if you want «bob» to act like a cat and chase the «mouse», then you will need some way to continuous evaluate the current mouse position and the image position. For this I would use a Swing Timer, its simple …
Java: mouseDragged and moving around in a graphical interface
Presently, I’m developing a program that renders equations provided by the user in a Cartesian coordinate system. However, I’m facing an issue with the user being able to move the view around the coordinate system. With the current implementation of mouseDragged, the user can move the view to some extent, but when the user tries to move it again, the origin snaps back to the current position of the mouse cursor. Can you suggest a better way to allow the user to move around freely? Thank you in advance!
Provided is the code for the designated space for drawing.
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import javax.swing.JPanel; public class DrawingArea extends JPanel implements MouseMotionListener < private final int x_panel = 350; // width of the panel private final int y_panel = 400; // height of the panel private int div_x; // width of one square private int div_y; // height of one square private int real_y; private int real_x; private Point origin; // the origin of the coordinate private Point temp; // temporary point private static int y = 0; private static int x = 0; DrawingArea() < setBackground(Color.WHITE); real_****_panel; real_y = y_panel; setDivisionDefault(); setOrigin(new Point((real_x / 2), (real_y / 2))); setSize(x_panel, y_panel); addMouseMotionListener(this); >DrawingArea(Point origin, Point destination) < this.origin = origin; this.destination = destination; panel = new JPanel(); panel.setSize(destination.x, destination.y); panel.setLocation(origin); this.panel.setBackground(Color.red); panel.setLayout(null); >@Override public void paintComponent(Graphics g) < super.paintComponent(g); Graphics2D line = (Graphics2D) g; temp = new Point(origin.x, origin.y); line.setColor(Color.red); drawHelpLines(line); line.setColor(Color.blue); drawOrigin(line); line.setColor(Color.green); for (int i = 0; i < 100; i++) < // This is a test line //temp = this.suora(); temp.x++; temp.y++; line.drawLine(temp.x, temp.y, temp.x, temp.y); >> public void setOrigin(Point p) < origin = p; >public void drawOrigin(Graphics2D line) < line.drawLine(origin.x, 0, origin.x, y_panel); line.drawLine(0, origin.y, x_panel, origin.y); >public void drawHelpLines(Graphics2D line) < int xhelp= origin.x; int yhelp= origin.y; for (int i = 0; i < 20; i++) < xhelp+= div_x; line.drawLine(xhelp, 0, xhelp, y_panel); >xhelp= origin.x; for (int i = 0; i < 20; i++) < xhelp-= div_x; line.drawLine(xhelp, 0, xhelp, y_panel); >for (int i = 0; i < 20; i++) < yhelp-= div_y; line.drawLine(0, yhelp,x_panel, yhelp); >yhelp= origin.y; for (int i = 0; i < 20; i++) < yhelp+= div_y; line.drawLine(0, yhelp, x_panel, yhelp); >> public void setDivisionDefault() < div_x = 20; div_y = 20; >@Override public void mouseDragged(MouseEvent e) < //Point temp_point = new Point(mouse_x,mouse_y); Point coords = new Point(e.getX(), e.getY()); setOrigin(coords); repaint(); >@Override public void mouseMoved(MouseEvent e) < >>
This program enables the user to move the intersection of the axes to any point by dragging it. The point, indicated by origin , initially begins at the panel’s center.
import java.awt.Cursor; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import javax.swing.JFrame; import javax.swing.JPanel; /** * @see https://stackoverflow.com/a/15576413/230513 * @see https://stackoverflow.com/a/5312702/230513 */ public class MouseDragTest extends JPanel < private static final String TITLE = "Drag me!"; private static final int W = 640; private static final int H = 480; private Point origin = new Point(W / 2, H / 2); private Point mousePt; public MouseDragTest() < this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); this.addMouseListener(new MouseAdapter() < @Override public void mousePressed(MouseEvent e) < mousePt = e.getPoint(); repaint(); >>); this.addMouseMotionListener(new MouseMotionAdapter() < @Override public void mouseDragged(MouseEvent e) < int dx = e.getX() - mousePt.x; int dy = e.getY() - mousePt.y; origin.setLocation(origin.x + dx, origin.y + dy); mousePt = e.getPoint(); repaint(); >>); > @Override public Dimension getPreferredSize() < return new Dimension(W, H); >@Override public void paintComponent(Graphics g) < super.paintComponent(g); g.drawLine(0, origin.y, getWidth(), origin.y); g.drawLine(origin.x, 0, origin.x, getHeight()); >public static void main(String[] args) < EventQueue.invokeLater(new Runnable() < @Override public void run() < JFrame f = new JFrame(TITLE); f.add(new MouseDragTest()); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); >>); > >
Java — What is the right way to move the mouse in a, But I have a problem to move the mouse in the game. The movement acts strange it is jumping around at the x and y coordination even if I only add 1 to the y coordinate. The movment acts like this in every 3D game not only in minecraft. For the movement I use the integreated robot class. Here is the snipped I use for …
Simulate mouse move and key pressing
In this example we are going to see how to simulate mouse moves and key pressing events in a Java Desktop Application. This is a quite cool feature that you can use in many ways in your application. For example you can have an interactive “Help” option that shows the user how to perform a certain activity in your applcation. In short all you have to do in order to simulate mouse moves and key pressing events is:
- Create a new Frame and a new TextArea .
- Create a new Robot component.
- Use robot.mouseMove(xCoord, yCoord) to move the mouse pointer in the coordinates you wish.
- Use robot.mousePress(InputEvent.BUTTON1_MASK) to press the key want.
- Use robot.mouseRelease(InputEvent.BUTTON1_MASK) to release the key.
Let’s see the code snippet that follows:
package com.javacodegeeks.snippets.desktop; import java.awt.AWTException; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Frame; import java.awt.Robot; import java.awt.TextArea; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; public class SimulateMouseMoveAndKeyPress < public static void main(String[] args) < try < // 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(); // Add the components to the frame; by default, the frame has a border layout frame.add(textArea, BorderLayout.CENTER); // Show the frame int width = 300; int height = 300; frame.setSize(width, height); frame.setVisible(true); // These coordinates are screen coordinates int xCoord = 50; int yCoord = 100; // Move the cursor Robot robot = new Robot(); robot.mouseMove(xCoord, yCoord); // Simulate a mouse click robot.mousePress(InputEvent.BUTTON1_MASK); robot.mouseRelease(InputEvent.BUTTON1_MASK); // Simulate a key press robot.keyPress(KeyEvent.VK_H); robot.keyRelease(KeyEvent.VK_H); robot.keyPress(KeyEvent.VK_E); robot.keyRelease(KeyEvent.VK_E); robot.keyPress(KeyEvent.VK_L); robot.keyRelease(KeyEvent.VK_L); robot.keyPress(KeyEvent.VK_L); robot.keyRelease(KeyEvent.VK_L); robot.keyPress(KeyEvent.VK_O); robot.keyRelease(KeyEvent.VK_O); >catch (AWTException e) < System.out.println("Low level input control is not allowed " + e.getMessage()); >> >
This was an example on how to simulate mouse moves and key pressing events.