0

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();
    }
}

}

2
  • Make field a local variable, instead of an instance field. Commented Sep 22, 2017 at 17:29
  • If your Pane with the TextFields only have TextFields in it, then you need to used that Pane to retrieve the TextFields. Use pane.getChildren() in your addNumber(..) method. Commented Sep 22, 2017 at 18:32

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.