setPreferredSize不起作用

Doo*_*nob 5 java swing awt jpanel jframe

码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我将首选大小设置JPanel为600乘600并打包帧,但帧的大小仍为0乘0.

为什么这样,我该如何解决?

Fil*_*lto 8

正如您所说,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);
    }
}
Run Code Online (Sandbox Code Playgroud)