为什么我的 JFrame 在 Mac 开始时会随机收缩?

Why does my JFrame randomly shrink when starting on Mac?

在我的 mac 笔记本电脑上工作时,我最近注意到当程序启动时我的框架有时会缩小。它确实缩小了大约 70-90%。

它在 PC 上按预期工作,但在我试过的任何 mac 上都不行。我试图将它缩小一点(到下面的代码)但是从这里我找不到它不起作用的任何原因。我的一些朋友认为这可能与 mac 自己的 window 经理有关。我不知道。

我对此很陌生,仅供参考。

public class Worms extends JFrame{

    public static void main(String[] args) {
        new Worms();
    }

    private JButton startGame;
    public Worms(){
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        Container contentPane = this.getContentPane();
        //if i change it so it uses a new dimension not "screenSize" it works
        contentPane.setPreferredSize(screenSize);


        JPanel menu = new JPanel();

        startGame = new JButton("Start Game"); 
        menu.add(startGame);//or if i remove this button it also works
        this.add(menu);


        this.pack();
        this.setVisible(true);
    }
}

它从 "fullscreen" 开始,然后缩小到左角。如果我将它拖回到正常大小,它就会正常工作。

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

Container contentPane = this.getContentPane();
//if i change it so it uses a new dimension not "screenSize" it works
contentPane.setPreferredSize(screenSize);

内容窗格不应将首选大小设置为屏幕大小。那太大了,不考虑框架装饰或'chrome'。

这是一种不同的方法,应该可以跨系统可靠地工作。它设置框架的扩展状态。

import java.awt.*;
import javax.swing.*;

public class Worms extends JFrame{

    public static void main(String[] args) {
        new Worms();
    }

    private JButton startGame;
    public Worms(){
        JPanel menu = new JPanel();

        startGame = new JButton("Start Game"); 
        menu.add(startGame);
        this.add(menu);

        this.pack();
        // this should do what you seen to want
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        // this is just polite..
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.setVisible(true);
    }
}

请注意,应在事件调度线程上创建和更新 Swing/AWT GUI。为了简单起见,上面的例子没有添加。