【问题标题】:Using Document FIlter to filter multiple periods(.)使用文档过滤器过滤多个句点(.)
【发布时间】:2013-10-06 18:00:31
【问题描述】:

假设用户必须在 Jtextfield 中输入一个 Double 值,然后进行计算。
但是如果用户突然使用超过 1 个句点,它会触发 NumberFormatException,所以我假设解决方案是使用文档过滤器来过滤掉任何额外的句点或捕获异常并通知用户输入无效

目前使用 DocumentFilter 只允许数字和句点,但我的问题是如何过滤掉第二个句点

PlainDocument filter = new PlainDocument();
            filter.setDocumentFilter(new DocumentFilter() {
                    @Override
                    public void insertString(FilterBypass fb, int off, String str, AttributeSet attr) 
                    throws BadLocationException 
                    {
                    fb.insertString(off, str.replaceAll("[^0-9.]", ""), attr);
                    } 
                    @Override
                    public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr) 
                    throws BadLocationException 
                    {
                    fb.replace(off, len, str.replaceAll("[^0-9.]", ""), attr);
                    }
            });

            apm.setDocument(filter);

例子

无效 输入:1.2.2

有效 输入:1.22

【问题讨论】:

  • 不知道在说什么,对我有用,为了更好的帮助尽快发布SSCCE,简短,可运行,可编译
  • 我会将过滤器编码为根本不允许第二个周期。你试过什么?怎么不工作?你好@mKorbel!
  • 我自己,我会等待sscce。
  • @HovercraftFullOfEels - 我也使用 DocumentListener 来计算值。
  • 或者使用JFormattedTextField 如图here

标签: java swing jtextfield documentfilter


【解决方案1】:

我的建议是您可以更改覆盖的 insertStringreplace 方法,以便它检查在此插入之前是否已插入任何 ".",或者以“句点”的方式替换和更改过滤器如果用户随后插入 period 字符,则将替换为空白字符串。我已经说明如下:

@Override
public void insertString(FilterBypass fb, int off, String str, AttributeSet attr) 
                throws BadLocationException {
    String regExp;
    Document doc = fb.getDocument();
    if(doc.getText(0, doc.getLength()).indexOf(".") == -1){
        regExp = "[^0-9.]";
    } else {
        regExp = "[^0-9]";
    }
    fb.insertString(off, str.replaceAll(regExp, ""), attr);
}

@Override
public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr) 
                throws BadLocationException {
    String regExp;
    Document doc = fb.getDocument();
    if(doc.getText(0, doc.getLength()).indexOf(".") == -1){
        regExp = "[^0-9.]";
    } else {
        regExp = "[^0-9]";
    }
    fb.replace(off, len, str.replaceAll(regExp, ""), attr);
}

上面的代码只允许在设置了这个DocumentFilterDocument中插入一次“句点”。

【讨论】:

    【解决方案2】:

    是的,使用 try catch 块。在 try 块中实现快乐路径(即格式正确的数字)并在 catch 块中实现错误情况。例如,如果您想以红色突出显示框或弹出错误消息,您可以将该逻辑放入(或从中调用)catch 块。

    【讨论】:

      猜你喜欢
      • 2014-09-10
      • 1970-01-01
      • 2015-11-06
      • 1970-01-01
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      相关资源
      最近更新 更多