1

I'm trying to make a JTextField which will only allow numeric input and only allow two characters (in other words will only allow numbers 0-99). I've looked at some tutorials and attempted to limit input to only numbers so far. The problem with my code so far though is that is accepts all key inputs. I tried reversing the greater than and less than symbols and it stopped accepting any input at all. I believe the problem lies in the key character codes, but some help would be nice as I can't find anything helpful (everywhere I look has different keymaps for Java).

if(event.getSource() == txtMasterSound)
    {
        if(event.getKeyCode() < 0 || event.getKeyCode() > 9)
        {
            System.out.println("Your input was invalid");
            event.consume();
        }
        else
        {
            System.out.println("Your input was valid");
            return;
        }
    }

As for the limiting characters, I don't really know where to start, so some pointing in the right direction would also be nice.

Jake Stanger
  • 449
  • 1
  • 8
  • 24

2 Answers2

8
  1. Use a JFormattedTextField instead
  2. Or use a DocumentFilter on the field's Document that filters non-valid input.
  3. Or use an InputVerifier.

e.g., a DoumentFilter

import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

public class MyDocFilter {
   private static void createAndShowGUI() {
      JTextField field1 = new JTextField(10);
      PlainDocument doc = (PlainDocument) field1.getDocument();
      doc.setDocumentFilter(new DocumentFilter() {
         private boolean isValid(String testText) {
            if (testText.length() > 2) {
               return false;
            }
            if (testText.isEmpty()) {
               return true;
            }
            int intValue = 0;
            try {
               intValue = Integer.parseInt(testText.trim());
            } catch (NumberFormatException e) {
               return false;
            }
            if (intValue < 0 || intValue > 99) {
               return false;
            }
            return true; 
         }

         @Override
         public void insertString(FilterBypass fb, int offset, String text,
               AttributeSet attr) throws BadLocationException {
            StringBuilder sb = new StringBuilder();
            sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
            sb.insert(offset, text);
            if (isValid(sb.toString())) {
               super.insertString(fb, offset, text, attr);
            }
         }

         @Override
         public void replace(FilterBypass fb, int offset, int length,
               String text, AttributeSet attrs) throws BadLocationException {
            StringBuilder sb = new StringBuilder();
            sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
            int end = offset + length;
            sb.replace(offset, end, text);
            if (isValid(sb.toString())) {
               super.replace(fb, offset, length, text, attrs);
            }
         }

         @Override
         public void remove(FilterBypass fb, int offset, int length)
               throws BadLocationException {
            StringBuilder sb = new StringBuilder();
            sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
            int end = offset + length;
            sb.delete(offset, end);
            if (isValid(sb.toString())) {
               super.remove(fb, offset, length);
            }
         }
      });


      JPanel panel = new JPanel();
      panel.add(field1);

      JFrame frame = new JFrame("MyDocFilter");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(panel);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGUI();
         }
      });
   }
}
Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
-1

This might be a bit sloppy but you could add a listener which detects changes(when something is typed) and every time something is typed you check what is typed and if it isn't 0-9 you remove the last character and if it's more then 2 characters you remove the excess characters.

This will probably work(I haven't tried it) but I think that the JFormattedTextField is more professional.

gumba
  • 72
  • 1
  • 7
  • 1
    This won't work nicely because it will most likely render before your listener can update it. – Obicere Jan 07 '14 at 19:24
  • And your suggestion will fail when someone tries to use copy-paste to paste text into the JTextBox. You really don't want to do this. – Hovercraft Full Of Eels Jan 07 '14 at 19:31
  • @Obicere Yes you are probably right that's why I said that it is sloppy but it will probably do it's job. You could also just do the check when you submit the string. – gumba Jan 07 '14 at 19:33
  • @HovercraftFullOfEels Wont a copy-past register as a change? If it does you just have to make a smarter check or just check when submiting to prevent crashes, people probably wont try to type something which is invalid anyways. But I do not disagree with the JFormattedTextField I'm just saying that my method will probably work. – gumba Jan 07 '14 at 19:40
  • @gumba: it won't work if your listener is a KeyListener -- never use those with a JTextField. The original poster does not want his JTextField to even allow entry of invalid input -- so what other listener are you suggesting that could possibly fulfill this requirement? I can think of none other than what I've posted and used. Have you tested my suggestions and your own before posting this answer? – Hovercraft Full Of Eels Jan 07 '14 at 19:42
  • *"you could add a listener which detects changes"* that's rather obscure. I can think of about 3-4 listeners which might fall into this category. Can you be more speocifc... – MadProgrammer Jan 07 '14 at 19:42
  • @HovercraftFullOfEels No I haven't tried neither and I'm not saying that my method is better just that in most cases it will work. It was just a suggestion if nothing else works. – gumba Jan 07 '14 at 19:48
  • @MadProgrammer I'm pretty sure there is one which register any change. – gumba Jan 07 '14 at 19:51
  • 1
    That doesn't help the OP, but just adds to the confusion. – MadProgrammer Jan 07 '14 at 19:59