JFrame是否不能准确显示指定的宽度和高度值?

huangapple go评论57阅读模式
英文:

Does JFrame not accurately display specified width and height values?

问题

我正在使用Java构建一个简单的2D游戏。

我正在使用JFrame类,但我认为宽度和高度不是我指定的,或者可能是图形不正确。

以下是我的一些代码片段:

public final static int WIDTH = 600, HEIGHT = 900;
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT - 10);

JFrame显示了一个黑色的背景。然而,根据我给fillRect函数的参数,底部仍应该有一个10像素高的白色细条。但事实并非如此。只有在从框架高度减少30像素后,白色细条才真正开始显示。

感谢您的帮助。

英文:

I'm building a simple 2D game in Java.

I'm using the JFrame class, but I don't think the width and height are what I specified, or perhaps the graphics are incorrect.

Here are some snippets of my code:

public final static int WIDTH = 600, HEIGHT = 900;
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT - 10);

The JFrame is displaying a black background. However, based on the arguments I gave to the fillRect function, there should still be a 10px tall sliver of white at the bottom of the frame. This is not the case. The white sliver only really starts to show after a 30px decrease from the height of the frame.

Thanks for your help.

答案1

得分: 5

The JFrame size includes the borders so you need to allow for them. To facilitate dealing with this don't specify the width and height of the JFrame. I recommend doing the following.

JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(width, height));
frame.add(panel);
// add other components in the panel
frame.pack();
// center on screen.
frame.setLocationRelativeTo(null);
frame.setVisible(true);

Now your panel will be the specified size.

Note, if you're going to paint, make certain you override paintComponent(Graphics g) in JPanel and do your painting there.

@Override
public void paintComponent(Graphics g) {
   super.paintComponent(g);
   // your code here
}
英文:

The JFrame size includes the borders so you need to allow for them. To facilitate dealing with this don't specify the width and height of the JFrame. I recommend doing the following.

JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(width,height));
frame.add(panel);
// add other components in the panel
frame.pack();
// center on screen.
frame.setLocationRelativeTo(null);
frame.setVisible(true);

Now your panel will be the specified size.

Note, if your going to paint, make certain you override paintComponent(Graphics g) in JPanel and do your painting there.

@Override
public void paintComponent(Graphics g) {
   super.paintComponent(g);
   // your code here
}

</details>



huangapple
  • 本文由 发表于 2020年8月2日 04:46:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63209914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定