1

Is it possible to change the style(or any property) of a JavaFX node if the active controller is not the controller of that node?

For example, say I want to be able to change the color of an AnchorPane by clicking a button. The button and the AnchorPane have two different controllers. How would this be achieved in the simplest way possible?

I have looked into / tried using..

When following documentation on Nested Controllers, I came to a stand still after successfully getting an instance of the AnchorPane's root node - couldn't figure out how to actually change the AnchorPane.

When calling to a function in the AnchorPane's controller class that should achieve the desired effect, the AnchorPane reference would always return a null pointer error.

Shane
  • 115
  • 1
  • 3
  • 17
  • 1
    Can you post some of your code? – Steven Mar 03 '16 at 07:06
  • If you're using `` to load the second fxml file, then use the nested controllers approach. Of course, you can still do the second thing you suggested: create a method in the controller that updates the style. Then you just call that method. Without seeing code it's hard to know where/why you're stuck. – James_D Mar 03 '16 at 13:58

2 Answers2

0

Check my answer out to a similar question. It is kind of roundabout to pass data between controllers, but it is possible through the main class. My answer to a similar question is here.

Accessing node from outside its controller JavaFX - MVC

There is a tutorial linked that is also great where I learned how to do this myself.

Community
  • 1
  • 1
Brian Stallter
  • 159
  • 1
  • 1
  • 16
  • This example really only works when you have a kind of Controller that is like an edit or settings window that is more temporary, but you could use a similar method if it was a longer term controller. – Brian Stallter Mar 03 '16 at 07:20
0

You have multiple options. One of them would be to use the controller associated with the other Node this is thoroughly described here (If the information flow should be the other way round, you can pass and store the parent controller to/in the child controller):

Passing Parameters JavaFX FXML

Another option would be to use css selectors to access the other node Node, but this isn't clean design since it breaks encapsulation.

(I assumen in the following example the id property of the AnchorPane has the value "anchorPaneId" and that you have access to someNodeInTheSameScene, which is an arbitrary node in the same scene as the AnchorPane you're trying to access.)

Scene scene = someNodeInTheSameScene.getScene();
AnchorPane anchorPane = (AnchorPane) scene.lookup("#anchorPaneId");
Community
  • 1
  • 1
fabian
  • 80,457
  • 12
  • 86
  • 114