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();
}
}
}
fielda local variable, instead of an instance field.Panewith theTextFields only haveTextFields in it, then you need to used thatPaneto retrieve theTextFields. Usepane.getChildren()in youraddNumber(..)method.