Reputation: 340
How can I get the position of a node from a TreeView with onclick event in JavaFX?
Let's say when I click on the node (dolor sit amet,) selected with the black circle how can I get the position?
I have tried this with an event when a node is expanded:
root.addEventHandler(EventType.ROOT, (Event event) -> {
if (event.getEventType().getName().equals("BranchExpandedEvent")) {
TreeItem item = (TreeItem) event.getSource();
//here I want to know item position
}
});
Upvotes: 0
Views: 748
Reputation: 45746
The Node
you're talking about is known as the disclosureNode
and is accessible via the TreeCell
.
The disclosure node is commonly seen represented as a triangle that rotates on screen to indicate whether or not the TreeItem that it is placed beside is expanded or collapsed.
You can get the position of this Node
with properties such as Node.boundsInLocal
or Node.boundsInParent
. There are also methods in Node
to help convert between coordinate spaces (e.g. localToScene
, sceneToLocal
, etc...).
Also, the following code is suspect:
root.addEventHandler(EventType.ROOT, (Event event) -> {
if (event.getEventType().getName().equals("BranchExpandedEvent")) {
}
});
You shouldn't need to check the name of the EventType
. Instead, register the EventHandler
for the EventType
you want to listen for—in this case, TreeItem.branchExpandedEvent()
. For example, if your TreeItem
s have values of type String
:
// "root" is a TreeItem<String>
// "event" is a TreeItem.TreeModificationEvent<String>
root.addEventHandler(TreeItem.<String>branchExpandedEvent(), event -> {
// do something...
});
If you must check the EventType
inside the EventHandler
then test that the EventType
s are equal, not their names; it's less error-prone.
root.addEventHandler(Event.ANY, event -> {
if (event.getEventType().equals(TreeItem.branchExpandedEvent()) {
// do something...
}
});
I want to have this position and to add some other Nodes (Vertical line in my case to connect the treeitems at the same level) in the TreeView.
I haven't looked into it, but this sounds like it should be implemented by the TreeCell
. The TreeItem
shouldn't know much, if anything, about the view. In other words, handling this inside an event handler added to the root TreeItem
seems like the wrong place. Note, you can get the expanded status of a TreeItem
from within a TreeCell
as it has access to its TreeItem
.
Upvotes: 1