JavaFX TabPane: How to listen to selection changes


Question

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 TabPaneBuilder class)

I guessed this code would work but it doesn't react to tab selection changes.

@FXML
protected TabPane chatTabs;
.
.    
.
chatTabs.selectionModelProperty().addListener(
    new ChangeListener<SingleSelectionModel<Tab>> {
            @Override
            public void changed(ObservableValue<? extends SingleSelectionModel<Tab>> ov, SingleSelectionModel<Tab> t, SingleSelectionModel<Tab> t1) {
                System.err.println("changed");
            }
        }
    }
);
1
15
5/23/2017 12:26:08 PM

Accepted Answer

The right way to use change listener is this:

chatTabs.getSelectionModel().selectedItemProperty().addListener(
    new ChangeListener<Tab>() {
        @Override
        public void changed(ObservableValue<? extends Tab> ov, Tab t, Tab t1) {
            System.out.println("Tab Selection changed");
        }
    }
);

Why code in question didn't work? I guess its because your change listener listens to changes in "selectionModel" instead of "selectedItem"


Finding out when a tab has been added or removed is a little trickier:

tabs.addListener( (Change<? extends Tab> change) -> {
  while( change.next() ) {
    if( change.wasAdded() ) {
      for( final Tab tab : change.getAddedSubList() ) {
        System.out.println( "Tab Added: " + tab );
      }
    } else if( change.wasRemoved() ) {
      // ...
    }
  }
} );
36
12/5/2016 8:07:25 PM

Or in Java 8 using lambda expression....

chatTabs.getSelectionModel().selectedItemProperty().addListener((ov, oldTab, newTab) -> {
        System.err.println("changed");
    });

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon