views:

42

answers:

2

As in wen you run any output in a frame, every time you run the program it pops on a different position on the screen?

+1  A: 

Use java.util.Random's nextInt(int) along with JFrame.setLocation(int, int).

For example,

frame.setLocation(random.nextInt(500), random.nextInt(500));
Mark Peters
And GraphicsEnvironment/GraphicsDevice to get the screen size.
Michael Myers
+3  A: 

You can use the setLocation(int, int) of JFrame to locate a JFrame in a new location.

So, put this in the frame's constructor and use Random to generate a random location, and your frame will pop up in a random location every time.

Another option would be to override the setVisible(boolean) method of the JFrame.

public void setVisible(boolean visible){
    super.setVisible(visible);
    if (visible) {
        Random r = new Random();
        // Find the screen size
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension d = tk.getScreenSize();
        // randomize new location taking into account
        // the screen size, and current size of the window
        int x = r.nextInt(d.x - getWidth());
        int y = r.nextInt(d.y - getHeight());
        setLocation(x, y);
    }
}

The code located inside the if (visible) block could be moved inside the constructor. The getWidth() and getHieght() methods may not return the correct values that you expect though.

jjnguy