Answer the question
In order to leave comments, you need to log in
How to constrain JFrame window movement to screen borders?
There is an undecorated JFrame that I move manually with the function below. It turned out to block the movement of the left and top edges of the screen, but with the opposite trouble. In the comments, two ways I tried to do this for the right border. They work, but the window "jumps", instead of just stopping at the edge of the screen, as it does with the left and top edges. Can you tell me how I can fix the function so that it works as it should?
private void registerMouseEvents(JFrame parent) {
parent.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
mouseX = (int) e.getPoint().getX();
mouseY = (int) e.getPoint().getY();
}
});
parent.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
int newX = parent.getLocation().x + e.getX() - mouseX;
int newY = parent.getLocation().y + e.getY() - mouseY;
if (getLocation().x > newX)
newX = getLocation().x;
if (getLocation().y > newY)
newY = getLocation().y;
if (parent.getLocation().x + parent.getWidth() > width)
System.out.println("move outside right");
// newX = width - parent.getWidth(); // don't work
// newX = getLocation().x; // don't work
if (parent.getLocation().y + parent.getHeight() > heigth)
System.out.println("move outside bottom");
parent.setLocation(newX, newY);
}
});
}
width = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
heigth = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question