1

Sorry in advance for title, I don't quite know what this is called.

I'm trying to set up my JFrame so that when it crosses past the screens width (or height), it stops moving. This is the code I have so far...

public void moverMouseDragged(java.awt.event.MouseEvent evt) {
        int x = evt.getXOnScreen()-xMouse;
        int y = evt.getYOnScreen()-yMouse;
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int width2 = (int) screenSize.getWidth();
        int height2 = (int) screenSize.getHeight();
        if(this.getX()<0){x=0;}
        if(this.getY()<0){y=0;}
        if((this.getX()+width)>width2){x=width2;}
        if((this.getY()+height)>height2){y=height2;}
        this.setLocation(x, y);
        System.out.println(this.getY()+"\n"+this.getX());
    }
    public void moverMousePressed(java.awt.event.MouseEvent evt) {                                   
        xMouse = evt.getX();
        yMouse = evt.getY();
    }

This works only for the top, and left side of my screen. Its full of glitches, and I honestly don't know where to go from here.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Arc
  • 441
  • 1
  • 9
  • 26

1 Answers1

1

I fixed it :

public void moverMouseDragged(java.awt.event.MouseEvent evt) {
        int x = evt.getXOnScreen()-xMouse;
        int y = evt.getYOnScreen()-yMouse;

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int xScreen = (int) screenSize.getWidth();
        int yScreen = (int) screenSize.getHeight();
        //System.out.println(width+" "+height);

        if(x<0){x=0;}
        if(y<0){y=0;}
        if(y>(yScreen-height)){y=yScreen-height;}
        if(x>(xScreen-width)){x=xScreen-width;}

        this.setLocation(x, y);
        //System.out.println(this.getY()+"\n"+this.getX());
    }
    public void moverMousePressed(java.awt.event.MouseEvent evt) {                                   
        xMouse = evt.getX();
        yMouse = evt.getY();
    }

Does exactly what it is supposed to do: stops the JFrame from going past either 4 sides of the screen.

Arc
  • 441
  • 1
  • 9
  • 26
  • What happens if I set the position programatically ? – MadProgrammer Feb 21 '14 at 20:08
  • What happens if the window is not on the default screen? Or the default screen is not positioned @ 0x0 – MadProgrammer Feb 21 '14 at 20:38
  • @MadProgrammer Well this works on the default screen. If you're talking about duel monitors, this http://stackoverflow.com/questions/3680221/screen-resolution-java maybe has the answer you're looking for. I'm not using duel monitors, so I can't try this one out sorry. – Arc Feb 21 '14 at 20:59
  • 1
    @arc I'm well aware of that ;) was prompting you to make a more reusable solution ;) – MadProgrammer Feb 21 '14 at 21:11