如何在随机位置生成一个JFrame?

4

当你在框架中运行任何输出时,每次运行程序它都会弹出在屏幕的不同位置上吗?

3个回答

4
您可以使用JFramesetLocation(int, int)方法将JFrame定位到新位置。
因此,将此放置在框架的构造函数中,并使用Random生成随机位置,每次都会在随机位置弹出您的框架。
另一个选项是覆盖JFrame的setVisible(boolean)方法。
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);
    }
}

if (visible)块中的代码可以移动到构造函数中。但是,getWidth()getHieght()方法可能不会返回您期望的正确值。


2

使用java.util.RandomnextInt(int)方法与JFrame.setLocation(int, int)方法结合使用。

例如,

frame.setLocation(random.nextInt(500), random.nextInt(500));

2
使用GraphicsEnvironment/GraphicsDevice获取屏幕大小。 - Michael Myers

0
如果您收到类似于“无法从Random类型进行静态引用非静态方法nextInt(int)”的错误,您可以使用替代代码:frame.setLocation((int)Math.random(), (int)Math.random()); 希望这能帮到您!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接