quartaela
quartaela

Reputation: 2757

Reach a variable from another class (which is controller class of JavaFX)

I'm trying to implement a game on JavaFX. Moreover, I'm dealing with an FXML file so I have a main class and controller class. My question is how can I reach the objects of the main class from the controller class. To be more clear I will share a simple code.

This is main class:

public class JavaFXApplication1 extends Application {

    @Override
    public void start(Stage primaryStage) throws IOException {

        Parent root = FXMLLoader.load(getClass().getResource("Risk3.fxml"));

        // Main Pane
        BorderPane borderPane = new BorderPane();
        borderPane.setCenter(root);

        // Main scene
        Scene scene = new Scene(borderPane);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

So for example I want to reach root or borderPane from controller class which is:

public class SampleController implements Initializable {

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }
}

Should I make root and borderPane global and static or is there any another way to reach them ?.

Upvotes: 1

Views: 754

Answers (1)

Salah Eddine Taouririt
Salah Eddine Taouririt

Reputation: 26395

The root panel can simply reached from the FXML controller using

@FXML tag like any component.

<BorderPane  xmlns:fx="http://javafx.com/fxml" fx:id="root">
    ...
</BorderPane>

Upvotes: 1

Related Questions