Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX TabPane: How to listen to selection changes

Tags:

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");             }         }     } ); 
like image 367
Mohammad Jafar Mashhadi Avatar asked Jul 08 '13 09:07

Mohammad Jafar Mashhadi


2 Answers

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() ) {       // ...     }   } } ); 
like image 158
Mohammad Jafar Mashhadi Avatar answered Sep 28 '22 01:09

Mohammad Jafar Mashhadi


Or in Java 8 using lambda expression....

chatTabs.getSelectionModel().selectedItemProperty().addListener((ov, oldTab, newTab) -> {         System.err.println("changed");     }); 
like image 44
user3190916 Avatar answered Sep 28 '22 02:09

user3190916