Search code examples
javajavafxjavafx-2javafx-8

JavaFX get access to a Tab or TabPane from a TabContent(Node)


Is there a way to get a reference to Tab or TabPane without no improvised way if you have reference to only the Node inside the Tab for eg

TabPane tabPane = new TabPane();
Tab tab = new Tab();
tab.setText("new tab");
Rectangle drect = new Rectangle(200,200, Color.LIGHTSTEELBLUE);
tab.setContent(drect);
tabPane.getTabs().addAll(tab,new Tab("tab 2"));

assume i only have reference to drect how can i get tab. I am not interested in Node.setUserData() also drect.getParent().getClass().getName() returns TabPaneSkin anon inner class TabContentRegion: two strangers.

All i am trying to say is Node.getParent() should return the parent Node , general uni-knowledge ( node's representation in the scene graph can be traced with getParent() ), but, when it comes to Tabs its all wrong, hence my question

EDIT

Why i needed this, suppose you have TabPane consisting of soo many Tab, in one particular Tab you have a TreeViews as its Node-Content which is selected out of some conditions, and for that particular TreeView you have different Custom Cells because its TreeItems differ in UI and function- like changing styles binding Fonts& other bindables and Animating Tab hiding other Tabs in the TabPane, closing other Tabs

with this scenario following this approach seems legit for me as, you do not do unnecessary stuff, like exposing children to bad weather. :-)

Thanks Sir James_D


Solution

  • The Tab itself is not a Node, so you can't get the tab just by iterating through the scene graph in any way. You can get to the TabPane if you go up far enough in the hierarchy. For example:

    private TabPane findTabPaneForNode(Node node) {
        TabPane tabPane = null ;
    
        for (Node n = node.getParent(); n != null && tabPane == null; n = n.getParent()) {
            if (n instanceof TabPane) {
                tabPane = (TabPane) n;
            }
        }
    
        return tabPane ;
    }
    

    will return the nearest TabPane containing the node passed in, or null if the node is not in a tab pane.

    However, needing this just seems like your design is wrong. If you put a node in a tab pane, at some point you create a tab, so you should just organize your code so you have the reference to the tab available.