I am searching for how to get the selected tab from a TabPane
just by clicking on a button with JavaFX. I've tried to do it with the ChangeListener
but it doesn't work yet.
So how can I do that?
Tabs are added to the TabPane by using the getTabs() . Tabs in a TabPane can be positioned at any of the four sides by specifying the Side . A TabPane has two modes floating or recessed. Applying the styleclass STYLE_CLASS_FLOATING will change the TabPane mode to floating.
Here is an example of adding 3 tabs to a JavaFX TabPane : TabPane tabPane = new TabPane(); Tab tab1 = new Tab("Planes", new Label("Show all planes available")); Tab tab2 = new Tab("Cars" , new Label("Show all cars available")); Tab tab3 = new Tab("Boats" , new Label("Show all boats available")); tabPane. getTabs().
add(tab); tabPane. getSelectionModel(). select(tab); Normally, the tabs can be closed by clicking the (default) close icons in the header of the tab, and "Closed!" is printed to the screen.
Group class is a part of JavaFX. A Group contains the number of nodes. A Group will take on the collective bounds of its children and is not directly resizable. Group class inherits Parent class.
As with many JavaFX controls there is a SelectionModel
to get first.
tabPane.getSelectionModel().getSelectedItem();
To get the currently selected tab, or alternatively, getSelectedIndex()
for the index of the selected tab.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TabSelect extends Application {
@Override
public void start(Stage primaryStage) {
TabPane tabPane = new TabPane();
tabPane.getTabs().addAll(new Tab("tab 1"),
new Tab("tab 2"),
new Tab("tab 3"));
Button btn = new Button();
btn.setText("Which tab?");
Label label = new Label();
btn.setOnAction((evt)-> {
label.setText(tabPane.getSelectionModel().getSelectedItem().getText());
});
VBox root = new VBox(10);
root.getChildren().addAll(tabPane, btn, label);
Scene scene = new Scene(root, 300, 300);
primaryStage.setScene(scene);
primaryStage.show();
//you can also watch the selectedItemProperty
tabPane.getSelectionModel().selectedItemProperty().addListener((obs,ov,nv)->{
primaryStage.setTitle(nv.getText());
});
}
public static void main(String[] args) { launch(args); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With