2
我對JavaFX和我的跳棋遊戲都是超級新手,我想要展示誰將它置於我的主板之上。我已經閱讀了多個非常類似的問題,但它似乎並沒有讓我想去哪裏。我希望你可以幫助我!根據布爾值更改標籤JavaFX
我有下面的代碼FXML文件:
<HBox fx:id="topBox" alignment="TOP_CENTER" prefHeight="45.0" prefWidth="200.0" spacing="10.0" BorderPane.alignment="CENTER" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.SampleController">
<children>
<Label fx:id="labelTurn" text="test" />
<Button fx:id="buttonResign" alignment="CENTER" mnemonicParsing="false" onAction="#doResign" prefHeight="25.0" prefWidth="80.0" text="Resign" />
</children>
</HBox>
在我的主:
public class Main extends Application {
Checkers content = new Checkers();
BorderPane border = new BorderPane();
@Override
public void start(Stage primaryStage) throws Exception {
try {
border.setTop(FXMLLoader.load(getClass().getResource("Sample.fxml")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
border.setCenter(createContent());
Scene scene = new Scene(border);
primaryStage.setTitle("Checkers from main");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
我的控制器:
public class SampleController {
@FXML
private Label labelTurn;
@FXML
private HBox topBox;
@FXML
private Button buttonResign;
private Checkers content = new Checkers();
@FXML
void doResign(ActionEvent event) {
content.resign();
// System.exit(0); //TODO eine tatsächliche Methode eingeben!!
}
public void setLabelTurn(Label labelTurn) {
this.labelTurn = labelTurn;
String setLabelText() {
String s = " ";
if (content.getWhiteTurnPropValue()) {
labelTurn.setText("White, it is your turn.");
s = "White, it is your turn.";
return s;
} else {
labelTurn.setText("Black, it is your turn.");
s = "Black, it is your turn.";
return s;
}
}
@FXML
void initialize() {
assert buttonResign != null : "fx:id=\"buttonResign\" was not injected: check your FXML file 'Sample.fxml'.";
assert topBox != null : "fx:id=\"topBox\" was not injected: check your FXML file 'Sample.fxml'.";
assert labelTurn != null : "fx:id=\"labelTurn\" was not injected: check your FXML file 'Sample.fxml'.";
labelTurn.textProperty().setValue(setLabelText());
}
}
我的遊戲數據有BooleanProperty展示誰是它。它在每次成功移動後都會改變。
BooleanProperty whiteTurnProp = new SimpleBooleanProperty(true);
public BooleanProperty getWhiteTurnProp() {
return whiteTurnProp;
}
public void setWhiteTurnPropValue(Boolean whiteTurn) {
this.whiteTurnProp.setValue(whiteTurn);
}
public boolean getWhiteTurnPropValue() {
return this.whiteTurnProp.getValue();
}
據我所知,我需要將Label綁定到我在初始化方法中完成的值。但是當我玩牌時,我的遊戲類中的價值發生了變化,標籤保持不變。我如何更新標籤?我想我需要添加一個更改監聽器的東西,但我不知道如何做到這一點,更具體地說在哪裏。
非常感謝您的幫助!我縮短了我的代碼,希望它不會太長。
最佳, 麗莎
謝謝!這很好用! – Lisa