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");
}
}
}
);
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() ) {
// ...
}
}
} );