JavaFX: Binding TextArea to element of selected TreeItem (contained in TreeView)

后端 未结 1 1002
春和景丽
春和景丽 2021-01-22 23:58

I\'m building the following JavAFX and I\'m pretty new to it altogether. Here\'s what it looks like:

http://i.imgur.com/nfzQzIY.png

As you can see there\'s a

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-23 00:56

    I would not make a subclass of TreeItem just for that. It's designed to be used with any object. For the TextArea bindings, just bind and unbind in the selection changed listener.

    package treebind;
    
    import javafx.application.Application;
    import javafx.beans.property.SimpleStringProperty;
    import javafx.beans.property.StringProperty;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.scene.Scene;
    import javafx.scene.control.TextArea;
    import javafx.scene.control.TreeItem;
    import javafx.scene.control.TreeView;
    import javafx.scene.layout.HBox;
    import javafx.stage.Stage;
    
    public class TreeBind extends Application {
    
        @Override
        public void start(Stage primaryStage) {
    
            TreeItem treeItemRoot = new TreeItem<>(new Plug("root","a"));
            TreeView treeView = new TreeView<>(treeItemRoot);
            for (int i=0;i<10;i++)
                treeItemRoot.getChildren().add(new TreeItem<>(new Plug("name"+String.valueOf(i),"")));
            treeView.setMinWidth(150);
    
            final TextArea ta1 = new TextArea();
    
            treeView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
                @Override
                public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                    if (oldValue!=null){
                        ((TreeItem)oldValue).getValue().s1.unbindBidirectional(ta1.textProperty());
                        ta1.clear();
                    }
                    if (newValue!=null){
                        ta1.setText(((TreeItem)newValue).getValue().s1.getValue());
                        ((TreeItem)newValue).getValue().s1.bindBidirectional(ta1.textProperty());
                    }
                }
            });
    
            HBox root = new HBox();
            root.getChildren().addAll(treeView,ta1);
            Scene scene = new Scene(root, 400, 300);
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        private class Plug{
            public final StringProperty name, s1;
    
            Plug(String name, String s1){
                this.name = new SimpleStringProperty(name);
                this.s1 = new SimpleStringProperty(s1);
            }
            @Override
            public String toString(){
                return name.getValue();
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题