Model ID for Node in JavaFX 2 TreeItem

Is there a way to save the identifier of the model object or the model object itself in JavaFX 2 TreeItem<String> ? There is only Value for storing text ...

I populate the TreeView from the list of model objects and should find it when the user clicks node. I'm used to working with Value and Text in .NET Windows Forms or HTML, and I'm afraid I can't adapt this way of thinking to JavaFX ...

+1
source share
2 answers

You can use any objects with TreeView, they just have to override toString() to represent or extend javafx.scene.Node

eg. for the following class:

 private static class MyObject { private final String value; public MyObject(String st) { value = st; } public String toString() { return "MyObject{" + "value=" + value + '}'; } } 

TreeView should be created as follows:

 TreeView<MyObject> treeView = new TreeView<MyObject>(); TreeItem<MyObject> treeRoot = new TreeItem<MyObject>(new MyObject("Root node")); treeView.setRoot(treeRoot); 
+4
source

I have the same problem as the OP. In addition, I want to bind the value displayed in the TreeItem to an object property. This is not complete, but I am experimenting with the following helper class, where I pass the "custom object" (or element) to be referenced in the TreeItem, and valueProperty (which, in my case, is the property of the element) to bind to the value of the TreeItem. value.

 final class BoundTreeItem<B, T> extends TreeItem<T> { public BoundTreeItem(B item, Property<T> valueProperty) { this(item, valueProperty, null); } public BoundTreeItem(B item, Property<T> valueProperty, Node graphic) { super(null, graphic); itemProperty.set(item); this.valueProperty().bindBidirectional(valueProperty); } public ObjectProperty<B> itemProperty() { return itemProperty; } public B getItem() { return itemProperty.get(); } private ObjectProperty<B> itemProperty = new SimpleObjectProperty<>(); } 
+1
source

Source: https://habr.com/ru/post/945460/


All Articles