JavaFX TabPane: How to listen to selection changes

前端 未结 4 1229
温柔的废话
温柔的废话 2021-01-03 23:47

I want to do some actions when user goes from one tab to another, since i made my form design with Scene Builder I cannot use code mentioned here (He used TabPaneBuild

4条回答
  •  猫巷女王i
    2021-01-04 00:40

    In addition to MJafar Mash answer above, you can use "selectedIndexProperty()" to get the index of the selected tab instead of "selectedItemProperty()" which gets the selected tab itself.

    chatTabs.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener (){
         @Override
         public void changed(ObservableValue observable, Number oldValue, Number newValue) {
               int selectedIndex = newValue.intValue();
               //where index of the first tab is 0, while that of the second tab is 1 and so on.
         }
     });
    

    And this is the lambda expression version of it

    chartTabs.getSelectionModel().selectedIndexProperty().addListener( (observable, oldValue, newValue) -> {
           int selectedIndex = newValue.intValue();
           //where index of the first tab is 0, while that of the second tab is 1 and so on.
    });
    

提交回复
热议问题