سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top