emberdex
emberdex

Reputation: 355

JavaFX - cannot access variable from view controller in EventHandler

I have code that looks like this for my EventHandler:

public EventHandler<MouseEvent> handleMouseClickedEvent = new EventHandler<MouseEvent>() {
    @Override
    public void handle(MouseEvent event) {
        // Grab the Pane from the event.
        Pane p = (Pane) event.getSource();

        // Set the colour of that pane.
        String colour = ViewController.brushColourPicker.getValue().toString();
        p.setStyle("-fx-background-color: " + colour);
    }
};

brushColourPicker cannot be accessed from the static context within the EventHandler - if I make the variable static in my view controller, I get NPEs. I also cannot use a getter, as the getter has to be static, which prevents access to my variable.

Any help is greatly appreciated.

Upvotes: 1

Views: 881

Answers (1)

arxakoulini
arxakoulini

Reputation: 733

In order to access the view elements of a controller from other classes one can do the following:

First, create a class to store your Controller(s) reference(s).

public class Controllers {

        private static MainController mainController;

        public static MainController getMainController() {
            return mainController;
        }

        public static void setMainController(MainController mainController) {
            Controllers.mainController = mainController;
        }

        public static void setMainControllerLoader(FXMLLoader mainControllerLoader) {
            Controllers.mainController = mainControllerLoader.getController();
        }
}

Then, do the following:

public class MainController
{
    // view elements..

    public void initialize()
    {
        Controllers.setMainController(this);
        // ...
    }
}

Or:

        Parent root;
        FXMLLoader loader;
        try {
            loader = new FXMLLoader(getClass().getClassLoader().getResource("path/to/yourFxml.fxml"));
            root = loader.load();
            Controllers.setMainControllerLoader(loader);
        } catch (IOException e) {
            // Failed to load fxml
        }
        Stage stage = new Stage();
        stage.setScene(new Scene(root, 600, 400));

Now you can call Controllers.getMainController() from any class and access the controller's view elements e.g. Controllers.getMainController().mainPane.setVisible(false)

Upvotes: 2

Related Questions