JavaFX:如何通过引用textarea来选择textarea所在的选项卡?

时间:2016-12-01 01:37:58

标签: javafx

JavaFX:如何通过引用textarea来选择textarea所在的选项卡?

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:2)

您可以通过节点层次结构,直到找到样式类为Node的节点作为父节点的tab-content-area。这是Tab的内容节点。根据这些信息,您可以找到相应的Tab

public static Tab findTab(Node node, TabPane tabPane) {
    if (tabPane == null) {
        throw new IllegalArgumentException();
    }

    // find content node that contains node
    Node parent = node.getParent();
    while (parent != null && !parent.getStyleClass().contains("tab-content-area")) {
        node = parent;
        parent = node.getParent();
    }

    // root reached before reaching the content of a tab
    if (parent == null) {
        return null;
    }

    // find appropriate tab 
    for (Tab tab : tabPane.getTabs()) {
        if (tab.getContent() == node) {
            return tab;
        }
    }
    return null;
}

@Override
public void start(Stage primaryStage) {
    TabPane tabPane = new TabPane();
    TextArea textArea1 = new TextArea();
    TextArea textArea2 = new TextArea();

    Tab tab1 = new Tab("tab1", textArea1);

    // wrap some parent to show this is working too
    Tab tab2 = new Tab("tab2", new StackPane(textArea2));
    tabPane.getTabs().addAll(tab1, tab2);

    ChangeListener<String> textChangeListener = (observable, oldValue, newValue) -> {
        // get node containing the property
        Node sourceNode = (Node) ((ReadOnlyProperty) observable).getBean();

        // find corresponging tab and select it
        Tab tab = findTab(sourceNode, tabPane);
        if (tab != null) {
            tabPane.getSelectionModel().select(tab);
        }
    };
    textArea1.textProperty().addListener(textChangeListener);
    textArea2.textProperty().addListener(textChangeListener);

    // add some text to the text areas alternatingly
    Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(2), new EventHandler<ActionEvent>() {

        private int num = 1;

        @Override
        public void handle(ActionEvent event) {
            textArea1.appendText("\n" + num);
            num += 2;
        }
    }), new KeyFrame(Duration.seconds(4), new EventHandler<ActionEvent>() {

        private int num;

        @Override
        public void handle(ActionEvent event) {
            textArea2.appendText("\n" + num);
            num += 2;
        }
    }));
    timeline.setCycleCount(Animation.INDEFINITE);
    timeline.play();

    Scene scene = new Scene(tabPane);

    primaryStage.setScene(scene);
    primaryStage.show();
}