Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

This is because the JFrames co-ordinates are starting at the top left corner including the title bar. You need to add the height of the title bar to your y co-ordinate to make it show in the top left corner.

Draw the Rect in a JPanel.

JPanel panel = new JPanel();
this.add(panel) //Add the panel to the frame and draw from there
                //Provided the class extends a JFrame
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top