clearing JTexxtField when input restricted to Integers

102 views Asked by At

I have a JTextFieldand I am trying to clear the text of the field by using textfield.setText(null);.But I an using document filter to restrict input to integers.Due to this it shows run time error.What shoul i do?

here is my code snippet

    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

There are 1 answers

1
RAJIL KV On BEST ANSWER

used keylistener instead of document filter and its working fine.

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().beep(); e.consume(); } } });