如何在JavaFX中获取选定的TabPane选项卡?

8
我正在寻找如何通过JavaFX中的按钮单击来获取TabPane中所选选项卡。我尝试使用ChangeListener,但它还没有起作用。那么我该怎么做呢?
2个回答

14

和许多JavaFX控件一样,首先需要有一个SelectionModel

tabPane.getSelectionModel().getSelectedItem();用于获取当前选定的标签页,或者使用getSelectedIndex()获取所选标签页的索引。

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); }

}

你能给我一些例子吗? - MadPro

2

tabPane.getSelectionModel().getSelectedIndex().


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接