【问题标题】:How can you generate a JFrame in a Random Location?如何在随机位置生成 JFrame?
【发布时间】:2011-02-24 05:44:42
【问题描述】:

就像在一个框架中运行任何输出一样,每次运行程序时它都会在屏幕上的不同位置弹出?

【问题讨论】:

    标签: java swing random jframe


    【解决方案1】:

    您可以使用JFrame 的setLocation(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.Random 的nextInt(int) 和JFrame.setLocation(int, int)。

      例如,

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

      【讨论】:

      • 和GraphicsEnvironment/GraphicsDevice获取屏幕尺寸。
      【解决方案3】:

      如果您收到Cannot make a static reference to the non-static method nextInt(int) from the type Random 等错误消息 您可以使用替代代码frame.setLocation((int)Math.random(), (int)Math.random());

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-26
        相关资源
        最近更新 更多