你可以有一个BooleanProperty叫做completedProperty,你也可以有initvalueProperty和finalValueProperty来存储游戏的积分,然后你可以简单的绑定completedProperty的值就好了
completedProperty.bind(initValueProperty.isEqualTo(finalValueProperty));
因此你甚至不再需要方法了。
在示例中,我刚刚放置了一个Button,它在按下时将当前值加一,并且我使用了 3 个属性来不断检查“游戏”状态。只要completedProperty 切换为“true”,就会出现带有“Game Over”文本的Label。
注意:我使用IntegerProperty来存储当前值和最终值,但你可以使用任何Property。
示例:
public class Main extends Application {
private IntegerProperty initValueProperty = new SimpleIntegerProperty(0);
private IntegerProperty finalValueProperty = new SimpleIntegerProperty(10);
private BooleanProperty completedProperty = new SimpleBooleanProperty();
@Override
public void start(Stage primaryStage) {
try {
BorderPane root = new BorderPane();
Scene scene = new Scene(root,400,400);
Button buttonPlusOne = new Button("+1");
root.setCenter(buttonPlusOne);
Text currValueText = new Text();
currValueText.textProperty().bind(initValueProperty.asString());
root.setBottom(currValueText);
// Increment current value
buttonPlusOne.setOnAction(e -> initValueProperty.set(initValueProperty.get()+1));
// Bind completed property: initValue equals finalValue
completedProperty.bind(initValueProperty.isEqualTo(finalValueProperty));
completedProperty.addListener((observable, oldValue, newValue) -> {
// Only if completed
if (newValue)
root.setTop(new Label("Game Over"));
});
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
可选(如fabian 所述)您甚至可以使用BooleanBinding 而不是属性来检查完成状态(在这种情况下您不需要completedProperty),例如:
BooleanBinding completed = initValueProperty.isEqualTo(finalValueProperty);
completed.addListener((observable, oldValue, newValue) -> {
// Only if completed
if (newValue)
root.setTop(new Label("Game Over"));
});
首先要了解 JavaFX this is a really good article 中的属性。