Reputation: 27
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;
}
}
}
Upvotes: 1
Views: 679
Reputation: 209225
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.
Upvotes: 4
Reputation: 116
You just need to make it static so you can access it using the class name directly and if your controllers are in different packages you need to add public because by default the visibility is package.
So you have to declare size like this :
public static int size = 5;
To access it you do :
SettingsStageController.size
Upvotes: -1