Saturn
Saturn

Reputation: 18149

Finding a specific node in a node's children list in JavaFX

    Button A = new Button();
    Button B = new Button();
    Button C = new Button();

    somePane.getChildren().add(A,B,C);

Now, let's go to the far future. I have a reference to somePane, and I am interested in accessing button B.

Technically, one could do something like

    somePane.getChildren().get(1); // returns the second button

However, I am not comfortable with this since it seems to be prone to errors.

It occurred to me that it would be pretty useful to have some sort of tag system. Like this:

    Button A = new Button();
    Button B = new Button();
    Button C = new Button();

    A.tag = "A";
    B.tag = "B";
    C.tag = "C";

    somePane.getChildren().add(A,B,C);

Then you could do

    somePane.getChildren().getByTag("B");  // returns the second button

Is there something like this for JavaFX?


You might be wondering:

Upvotes: 2

Views: 12693

Answers (1)

James_D
James_D

Reputation: 209320

Two ways come to mind immediately:

Use the userData property:

Button a = new Button();
a.setUserData("A");
Button b = new Button();
b.setUserData("B");
Button c = new Button();
c.setUserData("C");
somePane.getChildren().addAll(a, b, c);

// ...

private Node getByUserData(Parent parent, Object data) {
    for (Node n : parent.getChildren()) {
        if (data.equals(n.getUserData())) {
            return n ;
        }
    return null ;
}

Or, use a CSS id and the lookup() method. Note that this will only work once CSS has been applied to the node, which effectively means that they must be part of a live scene graph.

Button a = new Button();
a.setId("A");
Button b = new Button();
b.setId("B");
Button c = new Button();
c.setId("C");
somePane.getChildren().addAll(a, b, c);

// ...

Button button = (Button) somePane.lookup("#B");

Upvotes: 7

Related Questions