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");
}
}
}
);
Or in Java 8 using lambda expression....
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.And this is the lambda expression version of it
The right way to use change listener is this:
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:
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.