我有一个带有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);
}
我之前已经弄明白了,但我不记得该怎么做了。当我运行这个时会发生什么,我看到一些白色方块,其中应该有大的ScorePanel。
这是截图。我希望我的问题和代码是清楚的。
答案 0 :(得分:5)
JPanel
默认使用FlowLayout
,它尊重其子组件的首选大小。目前的首选大小可能是0 x 0
。覆盖getPreferredSize
进行设置。
ScorePanel score1 = new ScorePanel("Volume", 1) {
@Override
public Dimension getPreferredSize() {
return new Dimension(150, 100);
};
};
不要在组件上使用setSize
。而是如上所述设置首选大小,并确保调用JFrame#pack。