正如您所说,pack()将尝试安排窗口,以便将每个组件的大小调整为其preferredSize.
问题是布局管理器似乎是试图安排组件及其各自的preferredSize的人.但是,当您将布局管理器设置为null时,没有人负责.
尝试评论setLayout(null)行,你会看到结果.当然,对于一个完整的窗口,您将不得不选择并设置一个有意义的LayoutManager.
这对我很好:
import java.awt.Dimension;
import javax.swing.*;
public class Game extends JFrame {
private static final long serialVersionUID = -7919358146481096788L;
JPanel a = new JPanel();
public static void main(String[] args) {
new Game();
}
private Game() {
setTitle("Insert name of game here");
setLocationRelativeTo(null);
//setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
a.setPreferredSize(new Dimension(600, 600));
add(a);
pack();
setVisible(true);
}
}