我的JFrame总是变成几个像素太大了.

Mag*_*pel 3 java size swing jframe dimension

我正在用Java编写这个游戏,我只是将基于java.awt的所有窗口相关代码重写为javax.swing.不久之后,我意识到事情现在有点复杂了,所以我做了一些研究,并找到了如何绘制东西,如何设置JFrame的大小等等.但由于某种原因,我的JFrame的大小总是超出我指定的尺寸10个像素.在这种情况下,我希望它是640 x 640像素.

这是我的代码:

package chrononaut;

import java.awt.*;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;


@SuppressWarnings("serial")
public class GameJFrame extends JFrame 
    {

    //Background color:
    static Color bgrCol = new Color(12, 4, 64);

    //Size:
    final static int size = 640;

    //The component that does the actual drawing:
    static GameJComp drawingComp = new GameJComp();

    //Constructor:
    public GameJFrame()
        {
        //Calling super() and setting the title:
        super("Chrononaut");

        //Setting icon image:
        try 
        {
        Image icon = ImageIO.read(getClass().getResource("/icon/icon 1.png"));
        setIconImage(icon);
        }
        catch (IOException e) {}

        //make it closable:
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 


        //Setting the size:
        Container c = getContentPane();
        Dimension d = new Dimension(size, size);    //for some reason, it goes 10 pixels beyond the given values
        c.setPreferredSize(d);
        pack();

        //Adding the drawing component to the content pane:
        getContentPane().add(drawingComp);

        //Making sure the window size stays constant:
        setResizable(false);

        //Centering position:
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension s = tk.getScreenSize();
        setLocation(s.width/2-getWidth()/2, s.height/2-getHeight()/2);

        //Background color:
        setBackground(bgrCol);

        //Make it visible:
        setVisible(true);

        }


    public void drawAll()
        {
        drawingComp.drawAll();
        }

    public void closeGame()
        {
        dispose();
        System.exit(0);
        }

}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,JFrame边框内的空间看起来大小为650像素,而不是640,即使我调用setPreferredSize(d).我尝试制作Dimension d = new Dimension(size - 10,size - 10); 这似乎有效,但我不知道它会在其他平台上的天气.我没有在网络上的任何其他地方看到这个问题,所以我完全不知道为什么会这样做.:(

Mad*_*mer 8

这是与setResizable(false);您尝试设置窗口大小后使用相关的问题.

问题是(至少在Windows上),可调整大小和不可调整大小的窗口之间框架边框的大小不同.

打电话setResizable前打电话pack

如果您想要一种更好(通常更可靠)的窗口居中方式,请考虑使用

setLocationRelativeTo(null);
Run Code Online (Sandbox Code Playgroud)

代替

setLocation(s.width/2-getWidth()/2, s.height/2-getHeight()/2);
Run Code Online (Sandbox Code Playgroud)

Toolkit.getScreenSize 没有考虑任务栏占用的空间......