窗口大小小于应有的大小 [英] Window Size is smaller than it should be
问题描述
好的,所以我有了这个JFrame,上面有一个屏幕.我已将大小设置为800 x800.但是,创建的窗口比该窗口小.任务栏没有问题,因为它不是全尺寸的.
Alright so I've got this JFrame with a screen on it. I've set the size to 800 by 800. However the window is created smaller than that. It's not a problem with the taskbar because it's not fullsize.
package sharph;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Main extends JFrame {
public static String Title = "Game 1";
public static Dimension screenSize = new Dimension(800,800);
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle(Title);
frame.setSize(screenSize);
frame.setLocationRelativeTo(null);
frame.setResizable(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
Screen screen = new Screen();
screen.setSize(screenSize);
frame.add(screen);
frame.setVisible(true);
}
}
在屏幕类中,paint方法在边框应位于的位置周围绘制一个框:
In the screen class the paint method draws a box around where the border should be:
//Draw border
g.setColor(Color.RED);
g.drawRect(1, 1, 799, 799);
当我运行它时,窗口小于框,并且底部和右侧被切除.
When I run it, the window is smaller than the box and the bottom and right sides are cut off.
请注意第二张我手动调整大小以显示边框差异的图片.
Note the second picture I manually re-sized to show the border difference.
我意识到我把盒子的每一边都缩小了1个像素,但是差异远大于2个像素.
I realize that I have drawn the box 1 pixel smaller on each side, but the difference is much more than 2 pixels.
推荐答案
之所以会发生这种情况,是因为需要将内容压缩到边框大小减去边框的大小.
This happens because the content needs to squeezed into the size of the frame minus its borders.
结帐此问题和
Checkout this question and this question for a more detailed explanation
布局管理器还将覆盖您在Screen
组件上设置的size属性.无论哪种情况,都应该覆盖Screen
类的getPreferredSize
方法
The layout manager is also overriding the size property you set on the Screen
component. In either case, you should be overriding the getPreferredSize
method of the Screen
class
此外,您不应依赖魔术数字或有关组件实际大小的假设,而应改为使用getWidth
和getHeight
(我知道,这只是出于演示目的)
Also, you shouldn't be relying on magic numbers or assumptions about the actual size of the component, but should, instead, be using getWidth
and getHeight
instead (I know, it's just for demonstration purposes)
这篇关于窗口大小小于应有的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!