当输入限制为整数时清除JTexxtField

时间:2013-12-28 18:18:09

标签: java swing jtextfield documentfilter

我有一个JTextField,我试图通过使用textfield.setText(null);来清除字段的文本。但我使用文档过滤器来限制输入到整数。由于这显示运行时错误。我呢?

这是我的代码段

    PlainDocument doc = (PlainDocument) sid.getDocument();    
    doc.setDocumentFilter(new NumDocumentFilter());

    class NumDocumentFilter extends DocumentFilter {    

        @Override
        public void insertString(FilterBypass fb, int offset, String string,
               AttributeSet attr) throws BadLocationException {

            Document doc = fb.getDocument();    
            StringBuilder sb = new StringBuilder();    
            sb.append(doc.getText(0, doc.getLength()));    
            sb.insert(offset, string);    
            if (test(sb.toString())) {    
                super.insertString(fb, offset, string, attr);
            } else {

            }
    }

    private boolean test(String text) {

      try {    
         Integer.parseInt(text);    
         return true;    
      } catch (NumberFormatException e) {    
         return false;
      }
   }

    @Override
      public void replace(FilterBypass fb, int offset, int length, String text,
         AttributeSet attrs) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.replace(offset, offset + length, text);

      if (test(sb.toString())) {
         super.replace(fb, offset, length, text, attrs);
      } else {
         // warn the user and don't allow the insert
      }

   }

   @Override
   public void remove(FilterBypass fb, int offset, int length)
         throws BadLocationException {
      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.delete(offset, offset + length);

      if (test(sb.toString())) {
         super.remove(fb, offset, length);
      } else {
         // warn the user and don't allow the insert
      }``

   }

1 个答案:

答案 0 :(得分:-1)

使用了keylistener而不是文档过滤器,并且工作正常。

textfieldObject.addKeyListener(new KeyAdapter(){     public void keyTyped(KeyEvent e){       char c = e.getKeyChar();       if(!((c> ='0')&&(c< ='9')||          (c == KeyEvent.VK_BACK_SPACE)||          (c == KeyEvent.VK_DELETE))){         的getToolkit()哔();         e.consume();       }     }   });