我正在尝试使用不同的标签创建一个记分视图,并在变量状态发生变化时更新每个标记。所以说我有这个类可以扩展可观察性,它有可分离的方法来改变生活,时钟,食物和健康的价值。这些方法还通知观察者,在我的情况下是得分视图。
import java.util.Observable;
import com.codename1.ui.Display;
public class GameWorld extends Observable {
.....
private int lives = 3;
private int clock = 10;
private int food = 0;
private int health = 0;
.....
public void someMethodThatChangesValueOfLives {
lives--; //decreases lives
setChanged();
notifyObservers(lives);
}
public void someMethodThatChangesValueOfClock {
clock++; //increases clock
setChanged();
notifyObservers(clock);
}
public void someMethodThatChangesValueOfFood {
food += 30; //decreases lives
setChanged();
notifyObservers(food);
}
public void someMethodThatChangesValueOfHealth {
health += 30; //decreases lives
setChanged();
notifyObservers(health);
}
}
我的记分级别课程有不同的标签,用于存储生命,时钟,食物和健康。我的问题是我怎么想告诉更新方法更新哪个标签?说我的生活减少如何让它更新生命标签而不是时钟标签或其他标签?
import java.util.Observable;
import java.util.Observer;
import com.codename1.ui.Container;
import com.codename1.ui.Label;
public class ScoreView extends Container implements Observer {
private Label timeLabelText;
private Label timeLabelValue;
private Label livesLabelText;
private Label livesLabelValue;
private Label foodLabelText;
private Label foodLabelValue;
private Label healthLabelText;
private Label healthLabelValue;
...more labels
public ScoreView () {
timeLabelText = new Label("Time:");
timeLabelValue = new Label(" 0");
livesLabelText = new Label("Lives Left:");
livesLabelValue = new Label(" 3");
foodLabelText = new Label("Food Level:");
foodLabelValue = new Label("30");
healthLabelText = new Label("Health Level:");
healthLabelValue = new Label("10");
...more labels
this.addComponent(timeLabelText);
this.addComponent(timeLabelValue);
...add more labels to components
}
//How to tell update which label to update from the argument?
public void update (Observable o, Object arg) {
String clock = (String)arg;
timeLabelValue.setText(clock);
String lives = (String)arg;
livesLabelValue.setText(lives);
String food = (String)arg;
foodLabelValue.setText(food);
String health = (String)arg;
healthLabelValue.setText(health);
}
答案 0 :(得分:2)
属性非常适用于此,并且它们还具有其他一些便利功能。