0

I have a Dialog that accepts user input, and I want them to only be able to enter positive doubles only.

I tried adding a TextFormatter to the TextField in the initialize method of my controller class. Right now, it's not allowing me to input anything. I'm not sure if it's the TextFormatter that I used wrongly, or it's the regex. I tried a couple of regexes I found online, but nothing seems to work. Here's what I have tried so far:

/\(?[\d.]+\)?/

/\\d+\\.\\d+/

/\\(?[\\d.]+\\)?

Here is the code I added to the initialize method in my controller class.

public void initialize() {
        amount.setTextFormatter(new TextFormatter<Object>(change -> {
            if (!change.getText().matches("/\\(?[\\d.]+\\)?/")) {
                change.setText("");
            }
            return change;
        }));
    }

I'm not familiar with regexes as well, so I may not be aware that the ones I've used are completely wrong.

Thanks in advance.

Edit: I rewrote the question to follow the community guidelines. Sorry for posting a terrible question.

  • 3
    use a TextFormatter (instead of listener) - when stuck, come back with a [mcve] demonstrating what's not working as expected .. and __DO NOT__ delete and repost the exact same question https://stackoverflow.com/questions/68515126/how-to-add-event-handlers-to-textfield-to-filter-input - instead edit the previous to make it answerable – kleopatra Jul 25 '21 at 10:51
  • @kleopatra sorry, I'm new to StackOverflow and coding. I'll be sure not to repeat my mistake. As for the TextFormatter, I'm not sure how it really works. I'll add an edit to my question so it's much clearer. – Samuel Adrian Kosasih Jul 26 '21 at 15:40
  • Does this help? [How to force a double input in a TextField in JavaFX?](https://stackoverflow.com/questions/45977390/how-to-force-a-double-input-in-a-textfield-in-javafx) – Abra Jul 26 '21 at 17:46
  • @Abra Yes, thank you for your help. – Samuel Adrian Kosasih Jul 29 '21 at 06:31

0 Answers0