我正在用JavaFX创建一个棋盘游戏。我有两个控制器用于我的项目,并希望从主控制器访问变量和方法。我的主控制器具有大部分游戏逻辑和UI,但我希望有一个特殊情况的弹出窗口。现在我有弹出窗口,但想在弹出窗口控制器中使用主控制器中的变量。我能够从辅助控制器到主控制器获取变量,但不是相反。任何帮助将不胜感激。
以下是主控制器中打开新弹出窗口的代码:
public void newWindow() {
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("player.fxml"));
//Parent root = fxmlLoader.load();
Stage playerStage = new Stage();
playerStage.setTitle("Pick your move");
playerStage.initStyle(StageStyle.UNDECORATED);
playerStage.setScene(new Scene((Pane) fxmlLoader.load()));
playerStage.show();
ControllerPopup controller =
fxmlLoader.<ControllerPopup>getController();
this.controller = controller;
if(currentCard.getMoves() == 10){
controller.handleTen();
}
else if(currentCard.getMoves() == 11){
controller.handleEleven();
}
else{
controller.handleSeven();
}
disablePawns(bluePawns);
} catch (Exception e) {
e.printStackTrace();
}
}
这是辅助控制器:
public class ControllerPopup implements Initializable{
@FXML
private RadioButton button1,button2,button3,button4;
@FXML
private Button closeButton;
private RadioButton selectedButton;
private ToggleGroup group;
Controller controller;
@Override
public void initialize(URL location, ResourceBundle resources) {
group = new ToggleGroup();
button1.setToggleGroup(group);
button2.setToggleGroup(group);
button3.setToggleGroup(group);
button4.setToggleGroup(group);
}
public void handleTen(){
button1.setSelected(true);
button1.setText("Move forward 10");
button2.setText("Move backwards 1");
button3.setDisable(true);
button4.setDisable(true);
}
public void handleEleven(){
button1.setSelected(true);
button1.setText("Swap with another pawn");
button2.setText("Move forward 11");
button3.setDisable(true);
button4.setDisable(true);
}
public void handleSeven(){
button1.setSelected(true);
button1.setText("Move forward 1 and 6");
button2.setText("Move forward 2 and 5");
button3.setText("Move forward 3 and 4");
button4.setText("Move forward 7");
}
@FXML
public void handleCloseButtonAction(ActionEvent event) {
selectedButton = (RadioButton) group.getSelectedToggle();
Stage stage = (Stage) closeButton.getScene().getWindow();
stage.close();
}
public RadioButton getSelectedButton(){
return selectedButton;
}
答案 0 :(得分:0)
您可以在“辅助”控制器中创建适当的设置方法,并将值从主控制器传递给它们:
controller.setXXX(...);