2016-12-01 14 views

答えて

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(); 
} 
関連する問題