1

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
man
  • 35
  • 9

4 Answers4

1

When I remember swing textfields correctly, you can register as an input/keylistener and validate the input on every keystroke.

Smutje
  • 17,733
  • 4
  • 24
  • 41
  • You should never register a `KeyListener` to a text component when you want to modify the content going to the field - firstly you run the risk of generating a exception and secondly it won't handle the case where the user pastes text into the field. – MadProgrammer Feb 25 '14 at 00:57
1

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);  
    }
  });
}
Stimim
  • 26
  • 3
1

Make use of a DocumentFilter, this is what it's designed for.

Take a look at Text Component Features, in particular Implementing a Document Filter and here for examples

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

Just use a DocumentFilter to accept only integers.

import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException; 
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

public class InputInteger
{
private JTextField tField;
private JLabel label=new JLabel();
private MyDocumentFilter documentFilter;

private void displayGUI()
{
    JFrame frame = new JFrame("Input Integer Example");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    JPanel contentPane = new JPanel();
    contentPane.setBorder(
        BorderFactory.createEmptyBorder(5, 5, 5, 5));
    tField = new JTextField(10);
    ((AbstractDocument)tField.getDocument()).setDocumentFilter(
            new MyDocumentFilter());
    contentPane.add(tField); 
    contentPane.add(label);


    frame.setContentPane(contentPane);
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
}
public static void main(String[] args)
{
    Runnable runnable = new Runnable()
    {
        @Override
        public void run()
        {
            new InputInteger().displayGUI();
        }
    };
    EventQueue.invokeLater(runnable);
}
}

class MyDocumentFilter extends DocumentFilter{
    private static final long serialVersionUID = 1L;
    @Override
public void insertString(FilterBypass fb, int off
                    , String str, AttributeSet attr) 
                            throws BadLocationException 
{
    // remove non-digits
    fb.insertString(off, str.replaceAll("\\D++", ""), attr);
} 
@Override
public void replace(FilterBypass fb, int off
        , int len, String str, AttributeSet attr) 
                        throws BadLocationException 
{
    // remove non-digits
    fb.replace(off, len, str.replaceAll("\\D++", ""), attr);
}
}
ravibagul91
  • 20,072
  • 5
  • 36
  • 59