Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX: Create custom data attributes for nodes

Tags:

java

javafx

fxml

I am currently in need of custom attributes which I can fetch anytime. Is there any way to create custom data attributes for nodes and then get those values in javafx?

Lets assume I have the the follwing Button.

<Button text="Im a button" fooBar="I hold some value" />

Similar to: https://developer.mozilla.org/de/docs/Web/Guide/HTML/Using_data_attributes

Now in HTML I could simply do the following:

<div id="example" data-foobar="I hold some value"></div>

Then I could easily get the data like this:

document.getElementById("example").dataset.foobar;

Edit: I need more than 1 data property for a node because a node can hold various information.

like image 240
Asperger Avatar asked Dec 14 '22 03:12

Asperger


2 Answers

The data can be stored in the properties ObservableMap of a Node

Node node = ...
node.getProperties().put("foo", "bar");
...
Object foo = node.getProperties().get("foo");

Note however that some layout properties use this map too, so no property names similar to javafx properties / "static" properties should be used as key. To be sure you could create a custom key class that does not return true if an object of another type is passed as parameter to equals.

like image 163
fabian Avatar answered Dec 25 '22 03:12

fabian


To solve your problem you should to use userData it can be any object that you need.

node.setUserData("Hello world");
node2.setUserData(123);

etc.

If you need to set multiple values you can save your values in an array, list, json etc.

ArrayList<String> vals = new ArrayList();
vals.add("Hello");
vals.add("World");
node3.setUserData(vals);
//some code
ArrayList<String> result = (ArrayList) node3.getUserData();
like image 20
Vladlen Gladis Avatar answered Dec 25 '22 03:12

Vladlen Gladis