Window Size is smaller than it should be

大城市里の小女人 提交于 2020-01-14 19:42:31

问题


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

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.

I realize that I have drawn the box 1 pixel smaller on each side, but the difference is much more than 2 pixels.


回答1:


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

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

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)




回答2:


Instead of "screen.setSize(screenSize);" type "screen.setPreferredSize(screenSize);" and then after you type "frame.setVisible(true);" type "frame.pack()". You can also remove "frame.setSize(screenSize);" if you want to.



来源:https://stackoverflow.com/questions/16114834/window-size-is-smaller-than-it-should-be

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!