编程语言
首页 > 编程语言> > java – JTextArea仅包含数字,但允许负值

java – JTextArea仅包含数字,但允许负值

作者:互联网

我有一个JTextArea,只需要接受数字.这是我的代码:

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

适用于正数,但不适用于负数.我该如何解决这个问题?

编辑:对不起,AxisJTextFilter是在互联网上找到的,我忘记了.它的代码是:

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;
    }
}

解决方法:

尝试修改正则表达式(int验证方法containsOnlyNumbers).

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

这将接受以下数字:

> 1234
> -1234
> 1234
> 1234.1234

我希望它有所帮助

乌迪

标签:jtextarea,java,swing,negative-number,documentfilter
来源: https://codeday.me/bug/20190729/1576546.html