java 如何使用 JavaFX 从 TabPane 中获取选定的 Tab?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30276935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the selected Tab from the TabPane with JavaFX?
提问by MadPro
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.
我正在寻找如何TabPane
通过单击带有 JavaFX 的按钮来从 a 中获取选定的选项卡。我试过用 来做到这一点,ChangeListener
但还没有奏效。
So how can I do that?
那我该怎么做呢?
回答by brian
As with many JavaFX controls there is a SelectionModel
to get first.
与许多 JavaFX 控件一样,需要SelectionModel
先获得。
tabPane.getSelectionModel().getSelectedItem();
To get the currently selected tab, or alternatively, getSelectedIndex()
for the index of the selected tab.
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); }
}
回答by Navaneeth
tabPane.getSelectionModel().getSelectedIndex().
tabPane.getSelectionModel().getSelectedIndex()。