java: how to access an object through a string

1

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

Example:

private Label a15;

String celula = "a15";

(Label)celula.setText("texto");
    
asked by anonymous 30.11.2017 / 19:37

1 answer

1

You can use the lookup method. It gets an id and returns a node. But to use it you will need to set an id on 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();
        }
    }
    
01.12.2017 / 04:11