JTextArea only with numbers, but allowing negative values

前端 未结 2 1885
猫巷女王i
猫巷女王i 2021-01-21 03:01

I have a JTextArea which only has to accept numbers. This is my code:

DocumentFilter onlyNumberFilter = new AxisJTextFilter();
    final JTextArea areaTextoXMin          


        
相关标签:
2条回答
  • 2021-01-21 03:32

    Try modifying the regular expression (int the validation method containsOnlyNumbers).

    Pattern pattern = Pattern.compile("^[\\-\\+]?\\d+(\\.\\d+)?$");
    

    This will accept the following numbers:

    • 1234
    • -1234
    • +1234
    • 1234.1234

    I hope it helps

    Udi

    0 讨论(0)
  • 2021-01-21 03:42

    This is intended as a comment on Udi's excellent post, but I can't figure out how to do that.

    I think his pattern (d+) requires at least 1 digit, and it should be d? to allow 0-N digits. Because, as the user is typing, "-" is legal input. And a decimal point followed by no digits is always legal, especially while typing. It's only at the end (when you lose focus, etc., YMMV) that you can either require at least one digit, or, be accommodating and pragmatic and just treat the string "-" as 0.

    And when developing these kinds of regular expressions don't forget that the user might be copying and pasting.

    0 讨论(0)
提交回复
热议问题