【问题标题】:My JFrame always becomes a few pixels too big.我的 JFrame 总是变得太大了几个像素。
【发布时间】:2014-12-28 14:52:18
【问题描述】:

我正在用 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);
        }

}

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

【问题讨论】:

    标签: java swing jframe size dimension


    【解决方案1】:

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

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

    在拨打pack之前先拨打setResizable

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

    setLocationRelativeTo(null);
    

    而不是

    setLocation(s.width/2-getWidth()/2, s.height/2-getHeight()/2);
    

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

    【讨论】:

    • @MagnusAppel 是的,API 很痛苦 ;)
    猜你喜欢
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 2018-09-08
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多