我正在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合作伙伴是正确的,但是你的合作太高了:
Rectangle off screen http://i44.tinypic.com/4qn4g5.jpg
当我将y co-ords更改为27(矩形的高度)时,它会向下移动到我想要的位置:
Rectangle on screen http://i42.tinypic.com/2zpnors.png
知道为什么会这样吗?或者如何解决它?
答案 0 :(得分:4)
你是否覆盖了JFrame的paint(..)方法?坐标似乎位于窗口/ 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
答案 1 :(得分:1)
这是因为JFrames坐标从左上角开始,包括标题栏。您需要将标题栏的高度添加到y坐标,以使其显示在左上角。
答案 2 :(得分:0)
在JPanel中绘制Rect。
JPanel panel = new JPanel();
this.add(panel) //Add the panel to the frame and draw from there
//Provided the class extends a JFrame