java: how to access an object through a string

Asked

Viewed 63 times

1

I have a grid with several rows and columns and each cell has a Label. Each Label is named by column and row (example: a1, a2, B1, B2, etc), has how I access these Labels through a String?

Example:

private Label a15;

String celula = "a15";

(Label)celula.setText("texto");
  • Needs to be Label in a GridPane? You may not use a TableView and change the appearance of it with CSS? So much simpler to manipulate data.

1 answer

1

You can use the lookup method. It receives an id and returns a Node. But to use it you will need to set an id in the Labels.

Example:

public void start(Stage primaryStage) {
        try {
            GridPane gridPane = new GridPane();
            Label a1 = new Label("a1");
            a1.setId("a1");
            Label a2 = new Label("a2");
            a2.setId("a2");
            Label b1 = new Label("b1");
            b1.setId("b1");
            Label b2 = new Label("b2");
            b2.setId("b2");
            gridPane.add(a1, 0, 0);
            gridPane.add(a2, 1, 0);
            gridPane.add(b1, 0, 1);
            gridPane.add(b2, 1, 1);


            ((Label)gridPane.lookup("#a2")).setText("texto");

            Scene scene = new Scene(gridPane,400,400);
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
  • Thank you very much! I had even managed otherwise -- gridPane.getChildren().filtered(node -> node.getId().equals("a1")).forEach(node -> ((Label)node).setText("texto")); -- but this one looks much more appropriate.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.