public class ScoreView extends Container implements Observer {
private Label livesLabel;
private Label foodLevelLabel;
public ScoreView() {
// Create and add labels to the container
this.setLayout(new FlowLayout(Component.CENTER));
this.getStyle().getTextDecoration();
this.livesLabel = new Label("Lives: ");
this.foodLevelLabel = new Label("Food Level: ");
this.livesLabel.getAllStyles().setFgColor(ColorUtil.BLUE);
this.foodLevelLabel.getAllStyles().setFgColor(ColorUtil.BLUE);
this.add(livesLabel);
this.add(foodLevelLabel);
}
@Override
public void update(Observable o, Object arg) {
if (o instanceof GameWorld) {
GameWorld gw = (GameWorld) o;
livesLabel.setText("Lives: " + Integer.toString(gw.getChanceToLive()));
System.out.println("Updated lives label text: " + livesLabel.getText());
foodLevelLabel.setText("Food Level: " + Integer.toString(gw.getAnt().getFoodLevel()));
System.out.println("Updated food level label text: " + foodLevelLabel.getText());
}
revalidate();
repaint();
}
}
**ScoreView类在另一个类(Observable)中注册为Observer。执行update()方法 。print语句打印正确的标签值。我还在update()方法上调用了revalidate()。看起来容器没有更新新标签。我卡在这个 * 点上了。请帮助!
1条答案
按热度按时间gtlvzcf81#
我能想到的有三种可能性。我建议在调试器中放置一个断点,并验证其中哪一种适用:
ScoreView
类有多个示例。您向UI添加了一个示例,而另一个示例位于观察器回调中您只需要
revalidate()
,这里repaint()
是多余的。