Search code examples
javaswingintegerjtextfield

Input text only accepts numbers


I desinged a little swing GUI that has some JTextFields, but it has a validateVariables method that has to validate all the fields that are inside the interface, there's one JTextField called (IP) must accept only int Variables how can i set it up like that?

P.S the JTextfield was created it in netbeans with the palete tool.


Solution

  • This is the javadoc of JTextField http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html

    There is an example

    public class UpperCaseField extends JTextField {
    
      public UpperCaseField(int cols) {
        super(cols);
      }
    
      protected Document createDefaultModel() {
        return new UpperCaseDocument();
      }
    
      static class UpperCaseDocument extends PlainDocument {
    
        public void insertString(int offs, String str, AttributeSet a)
          throws BadLocationException {
    
            if (str == null) {
              return;
            }
            char[] upper = str.toCharArray();
            for (int i = 0; i < upper.length; i++) {
              upper[i] = Character.toUpperCase(upper[i]);
            }
            super.insertString(offs, new String(upper), a);
          }
        }
      }
    

    This example changes all user input to upper case. Just modify the insertString method, remove all non-digit characters, you can make your text field accept digits only.

    Example:

    public void insertString(int offs, String str, AttributeSet a)
        throws BadLocationException {
      if (str == null) {
        return;
      }
      super.insertString(offs, str.replaceAll("[^0-9]", ""), a);
    }
    

    ---- EDIT ----

    As @MadProgrammer said, DocumentFilter is another way to do so, for example:

    Document document = someJTextField.getDocument();
    if (document instanceof AbstractDocument) {
      ((AbstractDocument) doc).setDocumentFilter(new DocumentFilter() {
        public void insertString(DocumentFilter.FilterBypass fb, int offset,  
            String str, AttributeSet a) throws BadLocationException {  
          fb.insertString(offset, str.replaceAll("[^0-9]", ""), a);  
        }
      });
    }