I've got a JFrame with no decoration (no title bar, close button, etc) that I can drag around the screen using setLocation() and mouse position.
Unfortunately, the mouseExited event is called upon first move of the window...
- Move mouse into window and mouseEntered event is fired
- Click mouse and mousePressed event is fired.
- Drag mouse and mouseDragged event is fired, and setLocation is called.
- mouseExited event is fired, even though the mouse is still in the window!
- Moving mouse out of the window at this point will not fire mouseExited.
- Moving mouse out and back in will reset back to step 1.
How do I fix this problem, other than just manually testing mouse position on screen?
Edit: Here's a distilled version of the code
import java.awt.*;
import javax.swing.*;
import java.awt.Event;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
class DragNDropper implements MouseMotionListener, MouseListener
{
private int x, y;
private int dx, dy;
private boolean clicked;
private JFrame frame;
public DragNDropper(JFrame frame)
{
dx = dy = 0;
this.frame = frame;
}
public void mouseDragged(MouseEvent e)
{
x = e.getXOnScreen();
y = e.getYOnScreen();
frame.setLocation(x-dx, y-dy);
}
public void mouseMoved(MouseEvent e)
{
x = e.getXOnScreen();
y = e.getYOnScreen();
}
public void mouseClicked(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
clicked = true;
dx = e.getX();
dy = e.getY();
}
public void mouseReleased(MouseEvent e)
{
clicked = false;
}
public void mouseEntered(MouseEvent e)
{
System.out.println("Mouse entered");
}
public void mouseExited(MouseEvent e)
{
System.out.println("Mouse exited");
}
}
public class Program
{
public static void main(String[] argv)
{
JFrame jf = new JFrame();
DragNDropper dnd = new DragNDropper(jf);
jf.setSize(new Dimension(512, 512));
jf.addMouseListener(dnd);
jf.addMouseMotionListener(dnd);
jf.show();
}
}
Error: Main method not found in class DragNDropper, please define the main method as: public static void main(String[] args)
.. An MCVE includes a main. - Andrew ThompsonJFrame
in the class provided? How to run it as is ? Again this new edit does not conforms to MCVE document. In simple terms one should be able to simply copy and paste and run the code. In this case one has to first deletepublic
from one class and redundantimport
statements to make it run. - nIcE cOw