【问题标题】:Rectangle getting drawn in the wrong spot在错误的位置绘制矩形
【发布时间】:2019-09-04 03:31:54
【问题描述】:

我正在JFrame (854 x 480) 中创建游戏。我想在屏幕的右上角画一个Rectangle。像这样:

int x, y;
Rectangle rect;

public Foo() {
    x = 0;
    y = 0;
    
    rect = new Rectangle(x, y, 63, 27);
}

....

public void draw(Graphics g) {
    g.drawRect(rect.x, rect.y, rect.width, rect.height);
}

但是当我这样做时,框会从屏幕上拉出(x 坐标是正确的,但 y 坐标太高了:

当我将 y 坐标更改为 27(矩形的高度)时,它会向下移动到我想要的位置:

知道为什么会这样吗?或者如何解决?

【问题讨论】:

    标签: java jframe drawrectangle


    【解决方案1】:

    您是否覆盖了 JFrame 的 paint(..) 方法?坐标似乎在window/JFrame的坐标空间中,其中0/0包括非客户区(关闭框、标题栏等)。

    您应该创建一个单独的组件并将其添加到主框架的内容窗格中 - 只是一个非常小的示例 - 请注意我使用的是paintComponent(..):

    public static class MyPanel extends JPanel {
        @Override
        protected void paintComponent(final Graphics g) {
            super.paintComponent(g);
            final Graphics2D g2 = (Graphics2D) g;
            g2.setColor(Color.BLUE);
            g2.draw(new Rectangle2D.Float(8,8, 128, 64));
        }
    
    }
    

    添加到 JFrame 内容窗格(使用默认或自定义 LayoutManager):

    public class MyFrame extends JFrame {
        public MyFrame() {
           ...
           // since JDK 1.4 you do not need to use JFrame.getContentPane().add(..)
           this.add(new MyPanel());
        }
    }
    

    这应该可以解决问题。 Here's the corresponding section of the Java SE tutorial.

    【讨论】:

    • 不,这是一个新类,在 main 方法中,我的paint 方法正在调用这个 draw 方法,如下所示:foo.draw(g);
    【解决方案2】:

    这是因为 JFrames 坐标从左上角开始,包括标题栏。您需要将标题栏的高度添加到您的 y 坐标中,使其显示在左上角。

    【讨论】:

      【解决方案3】:

      在 JPanel 中绘制矩形。

      JPanel panel = new JPanel();
      this.add(panel) //Add the panel to the frame and draw from there
                      //Provided the class extends a JFrame
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-23
        • 1970-01-01
        • 2021-04-30
        • 1970-01-01
        • 1970-01-01
        • 2014-01-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多