1

I limit my JTextFields to accept only numbers. I was using following code for this.

  // my textboxes
  t1=new JTextField(10);
  t2=new JTextField(10);
  t3=new JTextField(10);

  // for the first one
  t1.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();
          }
        }
      });

Suppose I have 20 texboxes which need the same validation check. So do we need to write this code 20 times? Can I write a common method to implement this? I am new to Swing.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Nidheesh
  • 4,390
  • 29
  • 87
  • 150
  • 2
    Don't use a KeyListener whatever you do, since that has no effect on copy/paste and can mess up the JTextField in other ways. Use a DocumentFilter. You can find examples of this on this site and in the tutorials. For example: [here](http://stackoverflow.com/a/9346426/522444). – Hovercraft Full Of Eels Jun 25 '13 at 10:11
  • Have a look at this question, it should solve your problem: http://stackoverflow.com/questions/14215847/jtextfield-validation-for-numbers-and-one-decimal-point/14219756#14219756 More precisely, my answer. Thats a custom made component which accepts only number. – Branislav Lazic Jun 25 '13 at 10:12
  • You are getting a ton of the wrong answer. Pitiful. – Hovercraft Full Of Eels Jun 25 '13 at 10:14
  • yes we GET IT. There is a better way of filtering a JTextfield, using DOcumentFilter. But that is not the main point of his question. His question is about RE-USE – Oliver Watkins Jun 25 '13 at 10:18
  • @OliverWatkins: it is ***BAD*** advice. Please knock it off. The point is we should not mislead newbies because we're supposed to know better. – Hovercraft Full Of Eels Jun 25 '13 at 10:18
  • @OliverWatkins Read question again. – Branislav Lazic Jun 25 '13 at 10:19
  • 1
    Use a `JSpinner` as seen [here](http://stackoverflow.com/a/10021773/418556). – Andrew Thompson Jun 25 '13 at 10:23
  • See [this answer](http://stackoverflow.com/a/13424140/1076463) – Robin Jun 25 '13 at 11:20
  • possible duplicate of [Is there any way to accept only numeric values in a JTextField?](http://stackoverflow.com/questions/1313390/is-there-any-way-to-accept-only-numeric-values-in-a-jtextfield) – Robin Jun 25 '13 at 11:21
  • @Robin : I was asking for the solution to a specific issue I faced while playing with the above code. I don't think it is a duplication – Nidheesh Jun 25 '13 at 11:28
  • @OliverWatkins So what is the difference between creating a single `DocumentFilter` or a single `KeyListener`? Both are reusable, only the `DocumentFilter` was built for the task at hand. – MadProgrammer Jun 25 '13 at 11:33
  • possible duplicate of [Detecting JTextField "deselect" event](http://stackoverflow.com/questions/14305921/detecting-jtextfield-deselect-event) – David Kroukamp Jun 25 '13 at 12:14

6 Answers6

9

Again, use a DocumentFilter as this will handle copy and paste, this will allow filtering before the Document accepts the text:

import javax.swing.*;
import javax.swing.text.*;

public class DocListenerEg extends JPanel {
   private static final int FIELD_COUNT = 5;
   private JTextField[] fields = new JTextField[FIELD_COUNT];

   public DocListenerEg() {
      MyDocFilter myFilter = new MyDocFilter();
      for (int i = 0; i < fields.length; i++) {
         fields[i] = new JTextField(5);
         ((PlainDocument) fields[i].getDocument()).setDocumentFilter(myFilter);
         add(fields[i]);
      }
   }

   private class MyDocFilter extends DocumentFilter {
      public void insertString(DocumentFilter.FilterBypass fb, int offset,
            String text, AttributeSet attr) throws BadLocationException {
         for (char c : text.toCharArray()) {
            if (!Character.isDigit(c)) {
               return;
            }
         }
         fb.insertString(offset, text.toUpperCase(), attr);
      }

      public void replace(DocumentFilter.FilterBypass fb, int offset,
            int length, String text, AttributeSet attrs)
            throws BadLocationException {
         for (char c : text.toCharArray()) {
            if (!Character.isDigit(c)) {
               return;
            }
         }
         fb.replace(offset, length, text.toUpperCase(), attrs);
      }
   }

   private static void createAndShowGui() {
      DocListenerEg mainPanel = new DocListenerEg();

      JFrame frame = new JFrame("DocListenerEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 2
    +1.. @log_in see [this](http://stackoverflow.com/questions/14305921/detecting-jtextfield-deselect-event/14305952#14305952) too (shows other ways like `InputVerfier` and `JFormattedTextField`) – David Kroukamp Jun 25 '13 at 12:08
4

Try DocumentFilter as described in http://www.jroller.com/dpmihai/entry/documentfilter

0

Save your anonymus class into a variable:

KeyListener keyListener= 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();
      }
    }
  }

And then

t1.addKeyListener(keyListener);
t2.addKeyListener(keyListener);
t3.addKeyListener(keyListener);
...
darijan
  • 9,725
  • 25
  • 38
0

Create a class called :

NumberOnlyTextField

Make it extend JTextField, and add the addKeyListener(..) code in the constructor. There you have your very own number validation textfield.

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225
0

I would make a private boolean method (if it is only used in this class) or public if it it called for elsewhere as well eg. using reg ex:

public boolean checkToBeNumberInput(char c, KeyEvent e){
 if(!char c.matches("[0-9]")||
   (c == KeyEvent.VK_BACK_SPACE) ||
   (c == KeyEvent.VK_DELETE))) {
   getToolkit().beep();
   e.consume();
   return false;

 }
return true;
}

Then call for this boolean method and if it returns true:

if(checkToBeNumberInput()==false){
System.out.println("only numbers are allowed!");
}

This is a fast draft but I hope it helps someone

ghoulfolk
  • 326
  • 7
  • 17
0

//look event keypressed . : private void montoingresoKeyPressed(java.awt.event.KeyEvent evt) {

    if(Character.isLetter(evt.getKeyChar()))
    {
        //do what you want on this event, when key is pressed named evt
    }

}