javajframedrawrectangle

Rectangle getting drawn in the wrong spot


I am creating a game inside a JFrame (854 x 480). I am trying to draw a Rectangle in the upper right hand corner of the screen. like so:

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);
}

But when I do this, the box gets drawn off the screen (x co-ords are right, but y co-ords too high :

Rectangle off screen

When I change the y co-ords to 27 (the height of the rectangle), it moves down to where I want it to go:

Rectangle on screen

Any idea why this is happening? Or how to fix it?


Solution

  • Do you override the paint(..) method of your JFrame? The coordinates seem to be in the coordinate space of the window/JFrame, where 0/0 includes the non-client area (the close box, title bar and so on).

    You should create a separate component and add this to the content pane of your main frame - just a very tiny example - note that I am using 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));
        }
    
    }
    

    Add to JFrame content pane (use default or custom 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());
        }
    }
    

    This should do the trick. Here's the corresponding section of the Java SE tutorial.