So I have an integer number called “size” saved to a controller class called SettingsStageController.java and I want that variable to be accessed through my other controller class file called GameStageController.java but I can’t seem to find out how.
SettingsStageController.java
/* has the int size variable stored in this file */ int size = 5; public void startGame(ActionEvent event) throws IOException { FXMLLoader loader = new FXMLLoader(getClass().getResource("gameStage.fxml")); root = loader.load(); stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); // ti ston poutso scene = new Scene(root); stage.setTitle("DnB: " + Integer.toString(size) + "x" + Integer.toString(size) + " Game"); stage.setScene(scene); stage.show(); GameStageController gameStageController = loader.getController(); gameStageController.showPane(); }
GameStageController.java
public class GameStageController implements Initializable { @FXML Text testText; @FXML AnchorPane twoXtwoPane; @FXML AnchorPane threeXthreePane; @FXML AnchorPane fourXfourPane; @FXML AnchorPane fiveXfivePane; public void showPane() { switch (/* I WANT TO PUT THE "SIZE" NUMBER HERE" */) { case 2: twoXtwoPane.setDisable(false); twoXtwoPane.setVisible(true); break; case 3: threeXthreePane.setDisable(false); threeXthreePane.setVisible(true); break; case 4: fourXfourPane.setDisable(false); fourXfourPane.setVisible(true); break; case 5: fiveXfivePane.setDisable(false); fiveXfivePane.setVisible(true); break; default: twoXtwoPane.setDisable(false); twoXtwoPane.setVisible(true); break; } } }
Advertisement
Answer
If a method needs data to perform its functionality, then that data should be a parameter to the method. You should do:
public class GameStageController implements Initializable { // ... public void showPane(int size) { switch (size) { // ... } } }
and then of course
private int size = 5; public void startGame(ActionEvent event) throws IOException { // ... GameStageController gameStageController = loader.getController(); gameStageController.showPane(size); }
If your GameStageController
instance needs the size
variable later on, you can create an instance variable in that class, and set it in the showPane
method to the value passed as the parameter.