JavaFX TabPane: How to listen to selection changes

前端 未结 4 1153
温柔的废话
温柔的废话 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条回答
  •  一整个雨季
    2021-01-04 00:44

    I think a much better and more natural approach is using Tab.setOnSelectionChanged. Here's a complete little program that implements that approach. You can see a MUCH more complete example here: http://sandsduchon.org/duchon/cs335/fx020.html

    Note that you should also use Tab.isSelected to react correctly to selecting this tab or unselecting that this tab.

    import javafx.application.Application; // FX base, requires start(Stage)
    import javafx.stage.Stage;             // required by start (Stage)
    import javafx.scene.Scene;             // no scene --> no display
    
    import javafx.scene.control.TabPane;
    import javafx.scene.control.Tab;
    
    public class TabDemo extends Application {
    
       public void start (Stage stage) {
          TabPane tabPane = new TabPane ();
    
          Tab tba = new Tab ("one");
          Tab tbb = new Tab ("two");
    
          tabPane.getTabs().addAll (tba, tbb);
    
          tba.setOnSelectionChanged (e -> 
            System.out.println (
               tba.isSelected()?
               "a selected":
               "a unselected"
            )
          );
    
          Scene scene = new Scene (tabPane, 200, 50);
          stage.setScene (scene);
          stage.setTitle ("A Study of tab listeners");
          stage.show ();
       } // end start
    
    } // end class TabDemo
    

提交回复
热议问题