Search code examples
javaclassjavafxjavafx-8parent

Can a JavaFX node's parent class by accessed/determined?


Add Note: While I didn't find a clean solution to my stated problem, the root issue turned out to be that I was attempting to solve the "wrong problem". This is due to the timing of when initialize() is being called on the different JavaFX objects, and got ugly quickly (i.e., what happens if/when GridPane accesses Tab before the appropriate value(s) are set on Tab?). The real solution was to step back, reassess the implementation, and use setUserData() on GridPane from Tab, after Tab's values were correctly populated. Still a bit of a kludge, but much cleaner and reliable than what I was originally attempting, which was requiring the solution asked for below.

I am adding a GridPane to a Tab, and I need to access Tab.getText(). In the GridPane's initialize(), I can get the Parent using GridPane.getParent(). But, Parent doesn't implement getText(), and I cannot do ( Tab )Parent, nor use instanceof.

I've found mechanisms for gaining access to GridPane's controller, but I really don't want to do that unless necessary (i.e., I'd like for the GridPane instance to do "the right thing" without having external prodding).

I know the code snippet below doesn't compile/run, but is there a clean way to accomplish the idea behind the code?

@FXML private GridPane gridPane;

@FXML
public void initialize() {
    Parent parent = gridPane.getParent();

    if (parent instanceof Tab) {
        String foo = (( Tab )parent).getText();
    }
}

Solution

  • It's been a while since I asked this, and I have since modified the implementation and this is no longer an issue.

    The solution was to forgo declaring the controller in the FXML, and associating the controller to the FXMLLoader instance programmatically. This allows information to be passed to the GridPane's controller (either via constructor or other public methods) prior to the GridPane being loaded/instantiated.

    Doing it this way, the required information is already resident in the controller and can be accessed during initialization.

    Live and learn...