2013-10-06 56 views
0

可以说,用户必须在Jtextfield中输入Double值,然后才能计算出该值。
但是,如果用户突然使用多于1个周期,将触发一个NumberFormatException异常,所以我假定溶液将使用文档滤波器滤除任何额外的周期或捕捉异常并通知一个无效的输入的用户使用文档过滤器过滤多个句点(。)

Currenty使用某个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); 

无效 INPUT:1.2.2

有效 INPUT:1.22

+1

不知道在说什么,为我工作,为更好的帮助,尽快发布一个[SSCCE](http://sscce.org/),简短,可运行,可编译 – mKorbel

+1

我会编码过滤器,不允许第二个时期。你有什么尝试?它怎么不工作?你好@mKorbel! –

+0

我自己,我会等待sscce。 –

回答

0

我的建议是你可以改变重写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); 
} 

上面的代码将仅允许“期间”要插入只是在Document一旦此DocumentFilter被设定,它。

0

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