0

I added

this.getChildren().add(new HBox(new TextField("Some_Text ")));

in a class constructor, the class extends Java Fx Group. I wonder what to do to change the text in that TextField later.

For example, normally we can do this

TextField asdf = new TextField();
asdf.setText("Some_text");

but how can I change the text later in the previous example?

郭日天
  • 21
  • 4
  • you can try to get the reference by iterating through the child elements. In the example you provided a solution could look like this: `((TextField) ((HBox) this.getChildren().get(0)).getChildren().get(0)).setText("someText");` But this is a realy risky and way of achieving this because of the casts. A better way would be to just save the reference like you did in your second example. – Tobias Oct 24 '19 at 05:46
  • 1
    Store a reference to the `TextField` in an instance field of the class. – Slaw Oct 24 '19 at 07:49

1 Answers1

4

Using a reference

As Slaw states in a comment:

Store a reference to the TextField in an instance field of the class.

If you use FXML

If you use FXML, which is common for JavaFX apps, and place an fx:id attribute on a node, then use @FXML to inject the node into your controller, the reference will automatically be stored in the controller. In some cases, this kind of shifts the problem from "how do I get a reference to a node?" to "how do I get a reference to a controller?". If you need to answer the last question, then look at some of the suggestions in: Passing Parameters JavaFX FXML.

Using a lookup

If you really can't store a reference as an instance field in the class, for whatever reason, then set a css ID on the node and you can look it up later without having to write horrible code to traverse the scene graph to find it.

For example, replace:

this.getChildren().add(new HBox(new TextField("Some_Text ")));

with:

TextField textField = new TextField("Some_Text ");
textField.setId("myId");
this.getChildren().add(new HBox(textField));

Then sometime later, once the node is in the scenegraph, you can find the node by looking it up in the scene or a parent node by:

TextField myField = (TextField) scene.lookup("#myId");
if (myField != null) {
    // do something with myField
}

Note the cast in the lookup. By its nature, a runtime lookup based on css ids loses the compile-time type checking you get from a stored reference. For this, and other reasons, using stored references is generally the preferred way to reference things in JavaFX.

jewelsea
  • 150,031
  • 14
  • 366
  • 406