【问题标题】:Keeping the rectangle within JFrame将矩形保持在 JFrame 内
【发布时间】:2012-12-08 16:42:22
【问题描述】:

我知道我是个白痴,这就是为什么我无法弄清楚但我正在尝试使用paintComponent 绘制一堆大小和位置随机的矩形。我试图确保所有这些都画在框架内。我可以使用以下代码(sn-p)来做到这一点,但我想知道是否有比我将数字硬编码到程序中更好的方法来做到这一点。有没有我应该看看的方法可能是我正在寻找的?

这是覆盖paintComponent()方法的内部类:

class DrawPanel extends JPanel {
    public void paintComponent(Graphics g) {
        int red = (int)(Math.random()*256);
        int blue = (int)(Math.random()*256);
        int green = (int)(Math.random()*256);

        g.setColor(new Color(red, blue, green));
        //The following 4 lines keep the rects within the frame
        //The frame is 500,500
        int ht = (int)(Math.random()*400);
        int wd = (int)(Math.random()*400);

        int x = (int)(Math.random()*100);
        int y = (int)(Math.random()*100);

        g.fillRect(x,y,ht,wd);
    }
}

【问题讨论】:

  • 你有什么问题?您确定要在paintComponent(...) 内进行随机化,这样无论何时出于任何原因重新绘制 gui,矩形都会发生变化。你确定不想调用super.paintComponent(...) 方法吗?
  • 另外,你不应该使用 DrawPanel 的 getSize() 而不使用 JFrame 的大小吗?否则你会忽略它的标题栏等......
  • 查看相关示例here
  • 感谢 Reimeus、气垫船和卢卡斯。该程序甚至可以像以前那样工作。编码很丑,正如你们指出的那样,也有点错误。

标签: java swing user-interface jframe paintcomponent


【解决方案1】:

您的坐标和尺寸应基于DrawPanel 组件尺寸。同样使用Random.nextInt 而不是Math.random() 将更容易根据面板的当前大小保持在范围内:

Random random = new Random();
int ht = random.nextInt(getHeight());
int wd = random.nextInt(getWidth());

int x = random.nextInt(getWidth() - wd);
int y = random.nextInt(getHeight() - ht);

【讨论】:

  • 这就是我要找的。非常感谢。我也赞成所有其他答案,因为它们都很有帮助,但这解决了“问题”。
【解决方案2】:

我想知道是否有比我将数字硬编码到程序中更好的方法。

  • 在封闭的 JPanel、DrawPanel 上调用 getSize(),这样您就可以看到正在绘制的组件的实际边界。 (编辑:或 Lucas 推荐的 getWidth()getHeight() —— 1+ 到他的答案!)。
  • 此外,您通常希望在子级的覆盖中调用超级级的 paintComponent(...) 方法。
  • 此外,您通常希望在其他地方进行随机化,例如在 DrawPanel 的构造函数中,以免每次调整 GUI 大小时都更改矩形。

【讨论】:

  • 为了他的目的,调用 getHeight() 和 getWidth() 会不会更好,因为 getSize() 返回一个 Dimension?
  • @Lucas:两者都可以。顺便给你的答案加分。
  • 没错,使用单独的方法会稍微简单一些,但如果你知道自己在做什么,使用 getSize() 会更快。
【解决方案3】:

有一种方法可以获取您正在工作的面板的长度和宽度。

getHeight();
getWidth();

这些将返回您正在使用的 JPanel 的当前大小,这意味着如果您调整窗口大小,它实际上仍会在其中绘制它们。

http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#getWidth()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 2015-03-29
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    相关资源
    最近更新 更多