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


Question

    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:

  • Why don't I just make the button B a fixed property of my class?
    • Those buttons and panes are created dynamically. I can have several panes, all with their own "B" button.
  • Why don't I subclass the Button or Node class and add this functionality?
    • Makes sense and I could do it. I would rather have a simpler solution though.
1
2
7/26/2014 1:47:19 PM

Accepted Answer

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");
5
7/26/2014 1:57:27 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon