Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you generate a JFrame in a Random Location?

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?

like image 592
wam090 Avatar asked Oct 17 '25 07:10

wam090


2 Answers

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.

like image 71
jjnguy Avatar answered Oct 19 '25 20:10

jjnguy


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

For example,

frame.setLocation(random.nextInt(500), random.nextInt(500));
like image 35
Mark Peters Avatar answered Oct 19 '25 21:10

Mark Peters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!