JTextArea only with numbers, but allowing negative values

懵懂的女人 提交于 2019-12-02 00:12:32

问题


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

DocumentFilter onlyNumberFilter = new AxisJTextFilter();
    final JTextArea areaTextoXMin = new JTextArea(String.valueOf(xMin));
    ((AbstractDocument)areaTextoXMin.getDocument()).setDocumentFilter(onlyNumberFilter);

Works OK for positive numbers, but not for negative numbers. How can I fix that?

EDIT: Sorry, the AxisJTextFilter was found over the Internet and I forgot about that. Its code is:

import javax.swing.text.*;
import java.util.regex.*;

public class AxisJTextFilter extends DocumentFilter
{
    public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException
    {
        StringBuilder sb = new StringBuilder();
        sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
        sb.insert(offset, text);
        if(!containsOnlyNumbers(sb.toString())) return;
        fb.insertString(offset, text, attr);
    }
    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException
    {
        StringBuilder sb = new StringBuilder();
        sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
        sb.replace(offset, offset + length, text);
        if(!containsOnlyNumbers(sb.toString())) return;
        fb.replace(offset, length, text, attr);
    }
    public boolean containsOnlyNumbers(String text)
    {
        Pattern pattern = Pattern.compile("\\d*(\\.\\d{0,3})?");
        Matcher matcher = pattern.matcher(text);
        boolean isMatch = matcher.matches();
        return isMatch;
    }
}

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/7632387/jtextarea-only-with-numbers-but-allowing-negative-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!