-1

i am creating an program where the user has to enter the Number of dinnners on a Table which cant be zero , i am able to allow only integers as an input for the textField but how to exclude 0 and pop an error when user enters 0

Anzer Khan
  • 21
  • 4
  • 1
    This questions has many answers on SO. See this one for example: https://stackoverflow.com/questions/49918079/javafx-textfield-text-validation – c0der Apr 28 '20 at 05:16

2 Answers2

0

A possibility to handle this simply use a ChangeListener for your textfield. In this posts its explained how to do it : Value Change Listener for JavaFX's TextField

For a range listener it should be sth like this:

TextField textField = new TextField();
textField.textProperty().addListener((observable, oldValue, newValue) -> {
  int from = 0;
  int to = 200;
  if (newValue != null && !newValue.equals("")) {
    try {
      int number = Integer.parseInt(newValue);
      if (number < from || number > to) {
        throw new NumberFormatException();
      }
    } catch (NumberFormatException ignored) {
      field.setText(oldValue);
    }
  }
});

This avoids the user to insert numbers bigger or smaller than you want. But its not a perfect way to do it (just written down fast).

kayf
  • 87
  • 1
  • 11
  • Yes will be much better. But please use the search. There are a lot problems like this already solved. ;-) – kayf Apr 28 '20 at 05:57
0

I think this should work:

private void createListenerTextField (TextField textField, int LIMIT) {
        UnaryOperator<TextFormatter.Change> integerFilter = change -> {
            String newText = change.getControlNewText();
            if (newText.matches("-?([1-9][1-9]*)?")) {
                return change;
            }
            return null;
        };
        textField.setTextFormatter(new TextFormatter<>(new IntegerStringConverter(), null, integerFilter));
        textField.lengthProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue.intValue() > oldValue.intValue()) {
                // Check if the new character is greater than LIMIT
                if (textField.getText().length() >= LIMIT) {
                    // if it's LIMIT character then just setText to previous one
                    textField.setText(textField.getText().substring(0, LIMIT));
                }
            }
        });
    }

You can remove the LIMIT part if you want to let the user enter a huge number (I recommend to use it because the user can enter a bigint)