0

I want to create a program that if you click the up button, the window goes 50pixel up and so on. I am almost finished now, I want that the window cant go outside the current screen size. I want to do that in the Inner class.

`

class Listener extends WindowAdapter implements ActionListener{
        
        @Override
        public void windowOpened(WindowEvent e) {
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Dimension hHeight = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension wWidth = Toolkit.getDefaultToolkit().getScreenSize();
            setLocation(wWidth.width - getSize().width / 2, (hHeight.height - getSize().height) / 2);
            double width= wWidth.getWidth();
            if (e.getActionCommand().equals("UP") & yPosition > 0) {
                yPosition -= 10;
            }
            if (e.getActionCommand().equals("RIGHT") & xPosition <= width) {
                xPosition += 100;
            }
            if (e.getActionCommand().equals("DOWN")) {
                yPosition += 10;
            }
            if (e.getActionCommand().equals("LEFT") & xPosition > 0) {
                xPosition -= 10;
            }
            setLocation(xPosition,yPosition);
            
        }
    }

`

I make it for UP and LEFT for RIGHT and DOWN i don't manage it.

sebas
  • 1
  • 1
  • 1) the code doesn't make any sense since you first attempt to center the window and THEN apply the movement. Get rid of the centering logic. That code should be invoked when the first is first displayed. 2) You can't just check the x/y location of the frame. You also need to know the width/height to make sure the frame doesn't move outside the bounds. For example, you can check out: https://stackoverflow.com/a/54028681/131872. The move method will keep the balls within the bounds of the panel. Your logic will be simpler since you don't worry about change of direction. – camickr Dec 07 '22 at 15:28

0 Answers0