Ryan Koo
Ryan Koo

Reputation: 53

How to add multiple textfields to an arraylist JavaFX

I'm trying to make a UI that gets numbers from textfields that were added by pressing a button, adds the numbers, and then prints the console. I've figured out how to add textfields in an infinite number, but I can't seem to get all the numbers from each textfield and print out the sum. Whenever I put numbers into my textfield and press my 'add numbers' button, it only returns the number in the latest textfield added. Here's my code:

public VBox pane;
@FXML
private Button addButton;

@FXML
private TextField field;

@FXML
private void addNewTextField(ActionEvent event) {
    field = new TextField();

    field.textProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            if (!newValue.matches("\\d*")) {
                field.setText(newValue.replaceAll("[^\\d]", ""));
            }
        }
    });

    pane.getChildren().add(field);

}

@FXML
private void addNumbers(ActionEvent e) {

    ArrayList<Integer> numList = new ArrayList<>();

    try {
        ArrayList<Integer> list = new ArrayList<>();

        int result = Integer.parseInt(field.getText());

        list.add(result);



        int sum = 0;
        for (int i : list) {
            sum += result;
            System.out.println("The sum of numbers is  = " + sum);
        }

    } catch (NumberFormatException exception) {
        exception.printStackTrace();
    }
}

}

Upvotes: 0

Views: 1249

Answers (1)

jewelsea
jewelsea

Reputation: 159566

In this case the field should not be an instance variable at all, so it should not be annotated @FXML and should instead be declared within your method.

If you don't know what a local variable is and how it differs from an instance variable, read this tutorial on local variables.

Remove these lines:

@FXML
private TextField field;

Change the method body to:

private void addNewTextField(ActionEvent event) {
    TextField field = new TextField();
    . . .
}

Aside: You should never set a variable annotated @FXML to a new value (a reference will be injected by the FXMLLoader, and that should not be reassigned by the application programmer).

Upvotes: 1

Related Questions