As in wen you r开发者_开发百科un any output in a frame, every time you run the program it pops on a different position on the screen?
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.
Use java.util.Random
's nextInt(int)
along with JFrame.setLocation(int, int)
.
For example,
frame.setLocation(random.nextInt(500), random.nextInt(500));
If you receive an error such as Cannot make a static reference to the non-static method nextInt(int) from the type Random
you can use the alternative code, frame.setLocation((int)Math.random(), (int)Math.random());
Hope this helps!
精彩评论