Java 无论我设置了多大的尺寸,JPanels始终显示为小正方形

Java 无论我设置了多大的尺寸,JPanels始终显示为小正方形,java,swing,jpanel,Java,Swing,Jpanel,我有一个带有BorderLayout的JFrame类,它包含另一个扩展JPanel的类(ScorePanel)。这是JFrame类的相关代码,设置ScorePanels的构造函数没有调用该方法。gPanel是主要的游戏面板,但别担心 public void initialize() { //called by controller at the end if (Controller.DEBUG) System.out.println("View initialized"); J

我有一个带有BorderLayout的JFrame类,它包含另一个扩展JPanel的类(ScorePanel)。这是JFrame类的相关代码,设置ScorePanels的构造函数没有调用该方法。gPanel是主要的游戏面板,但别担心

public void initialize() { //called by controller at the end
    if (Controller.DEBUG) System.out.println("View initialized"); 
    JPanel scores = new JPanel();
    scores.setSize(1000,200);
    scores.setBackground(Color.BLACK);
    ScorePanel score1 = new ScorePanel("Volume", 1);
    ScorePanel score2 = new ScorePanel("Pitch", 2);
    scores.add(score1); scores.add(score2);
    scores.setVisible(true);
    scores.validate();
    this.add(scores, BorderLayout.SOUTH);
    this.add(gpanel, BorderLayout.CENTER); //main game panel
    this.validate();
    this.setVisible(true);
    this.repaint();
}
这是ScorePanel的相关代码:

private int score; //this current score
private String name; //this name
private int player; //this player

public ScorePanel(String n, int p){ //a JPanel that shows the player's name and score
    super();
    name = n;
    score = 0;
    player = p;
    setBackground(Color.WHITE);
    setSize(450,150);
    setVisible(true);
}
我以前就知道了,但我不记得该怎么办了。当我运行这个程序时,会发生什么?我看到一些白色的方块,它们应该是大的记分板

这是一个截图。我希望我的问题和代码是明确的


JPanel
默认情况下使用
FlowLayout
,该布局考虑其子组件的首选尺寸。当前首选的大小可能是
0 x 0
。覆盖
getPreferredSize
以设置此值

ScorePanel score1 = new ScorePanel("Volume", 1) {
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(150, 100);
    };
};
不要在组件上使用
setSize
。而是如上所述设置首选大小,并确保调用