JavaFX TabPane: How to set the selected tab

后端 未结 4 1816
一向
一向 2021-02-02 05:50

I have a Java Desktop Application with JavaFX 2 in it and in my FX I\'ve got a TabPane. I want to set the default tab. In other words I want to set a tab as selected. I found th

相关标签:
4条回答
  • 2021-02-02 06:21

    The SelectionModelis the right approach. You can get the default from your TabPane or assign your own implementation by using setSelectionModel(...). The default model should be good enough for the beginning.

    SingleSelectionModel<Tab> selectionModel = tabPane.getSelectionModel();
    

    Once you stored it in some local variable, you have different options to select a tab.

    selectionModel.select(tab); //select by object
    selectionModel.select(1); //select by index starting with 0
    selectionModel.clearSelection(); //clear your selection
    

    If you try to select a non existing tab, nothing will happen.

    0 讨论(0)
  • 2021-02-02 06:29

    To continue with Menai's answer heres how to refocus the opened tab/TabPane.

    SingleSelectionModel<Tab> selectionModel = TabPane.getSelectionModel();
    if(!Tabpane.getTabs().contains(tabName)) {
       TabPane.getTabs().add(tabName);
       selectionModel.select(tabPane);
    } else {
       selectionModel.select(tabPane); 
    }
    
    0 讨论(0)
  • 2021-02-02 06:31

    To simplify the above mentioned approach:

    myTabPane.getSelectionModel().select(myTab);
    
    0 讨论(0)
  • 2021-02-02 06:31

    If you work with statique tabs ,i mean your TabPane has statique number of tabs ,you can select your tab by this way :

     SingleSelectionModel<Tab> selectionModel = TabPane.getSelectionModel();
    
            selectionModel.select(tabName);
    

    If you work with dynamique tabs ,i mean your TabPane has dynamique number of tabs (add and remove tabs) ,you can select your tab by this way :

            if (!TabPane.getTabs().contains(tabName)) {
    
            TabPane.getTabs().add(tabName);
    
        }
        SingleSelectionModel<Tab> selectionModel = TabPane.getSelectionModel();
    
        selectionModel.select(tabPane);
    
    0 讨论(0)
提交回复
热议问题