Last active
August 16, 2019 21:14
-
-
Save ezhov-da/2c7f601792f468dc79ea080c2e882215 to your computer and use it in GitHub Desktop.
java mouse move window listener перетаскиваем форму frame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MouseMoveWindowListener mouseMoveWindowListener = new MouseMoveWindowListener(frame); | |
label.addMouseMotionListener(mouseMoveWindowListener); | |
label.addMouseListener(mouseMoveWindowListener); | |
class MouseMoveWindowListener extends MouseAdapter { | |
private Point diffOnScreen; | |
private Component component; | |
MouseMoveWindowListener(Component component) { | |
this.component = component; | |
} | |
@Override | |
public void mousePressed(MouseEvent e) { | |
SwingUtilities.invokeLater(() -> { | |
Point pressedPointLocationOnScreen = e.getLocationOnScreen(); | |
int x = pressedPointLocationOnScreen.x - component.getLocationOnScreen().x; | |
int y = pressedPointLocationOnScreen.y - component.getLocationOnScreen().y; | |
diffOnScreen = new Point(x, y); | |
}); | |
} | |
@Override | |
public void mouseDragged(MouseEvent e) { | |
SwingUtilities.invokeLater(() -> { | |
Point nowMouseLocation = e.getLocationOnScreen(); | |
Point point = new Point( | |
nowMouseLocation.x - diffOnScreen.x, | |
nowMouseLocation.y - diffOnScreen.y | |
); | |
SwingUtilities.convertPointFromScreen(point, component.getParent()); | |
component.setLocation(point); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment