M
M
Mimocodil2021-04-13 02:04:50
Java
Mimocodil, 2021-04-13 02:04:50

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?

function
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);
    }
  });
}


mouseX and mouseY are integer class variables that are not used anywhere else.
width and heigth are integer class variables; screen width and height values ​​are defined during class initialization:
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

1 answer(s)
D
Deiwan, 2021-04-20
@Deiwan

I didn’t quite understand what you meant, but if you need the button to automatically pop into the window, you need a layout (layout)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question