JavaFX: TextFields displayed from array, array updated / increased on button click – how to force the scene to redraw the updated array

Tags: , ,



I have a program that displays animals and their names:

    private int TOTAL_ANIMALS = 5;

    private TextField[] animals;
    private TextField[] names
public AnimalsApp  {
  animals = new TextField[TOTAL_ANIMALS];
  names = new TextFields[TOTAL_ANIMALS];
  for (int i = 0; i < TOTAL_ANIMALS; i++)  {
    animals[i] = new TextField();
    names[i] = new TextField();
  }
}
@Override
    public void start(Stage primaryStage) {
       GridPane grid = new GridPane();
       ...
       for (int i = 0; i < TOTAL_ANIMALS; i++)  {
         grid.add(animals[i], 0, i);
         grid.add(names[i], 1, i);
       }

The method associated with Add animal button:

public void addAnimals()  {
  animals = Arrays.copyOf(animals, TOTAL_ANIMALS + 1);
  names = Arrays.copyOf(names, TOTAL_ANIMALS + 1);

  animals[TOTAL_ANIMALS] = new TextField();
  names[TOTAL_ANIMALS] = new TextField();
  TOTAL_ANIMALS++;

  System.out.println("Animals updated");
}

The code inside addAnimals does execute, but the new text field doesn’t appear. How should I fix it?

Answer

You forgot to add the text fields to grid, just creating a textfield doesn’t show it you need to add it to your like you did in your start function. You would also need to make the GridPane a variable in the class.

public void addAnimals()  {
  animals = Arrays.copyOf(animals, TOTAL_ANIMALS + 1);
  names = Arrays.copyOf(names, TOTAL_ANIMALS + 1);

  animals[TOTAL_ANIMALS] = new TextField();
  names[TOTAL_ANIMALS] = new TextField();
  grid.add(animals[TOTAL_ANIMALS], 0, TOTAL_ANIMALS);
  grid.add(names[TOTAL_ANIMALS], 1, TOTAL_ANIMALS);
  TOTAL_ANIMALS++;

  System.out.println("Animals updated");
}


Source: stackoverflow