我有一个带有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();
}
Run Code Online (Sandbox Code Playgroud)
这是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);
}
Run Code Online (Sandbox Code Playgroud)
我之前想过这个,但我不记得该怎么做了.当我运行这个时会发生什么,我看到一些白色方块,其中大的ScorePanel应该是.
这是一个截图.我希望我的问题和代码是清楚的.

JPanelFlowLayout默认情况下使用它来尊重其子组件的首选大小.目前的首选尺寸可能是0 x 0.覆盖getPreferredSize以设置此项.
ScorePanel score1 = new ScorePanel("Volume", 1) {
@Override
public Dimension getPreferredSize() {
return new Dimension(150, 100);
};
};
Run Code Online (Sandbox Code Playgroud)
不要setSize在组件上使用.而是如上所述设置首选大小,并确保调用JFrame#pack.