简体   繁体   中英

Force User not to enter numeric entry in jTextField in java

如何锁定用户的键盘,以使用户无法在JTextField输入任何数字值?

javax.swing.InputVerifier

works well for most simple tasks.

Here's one I knocked out the other day:

public class TexFieldValidator extends InputVerifier {

   String regex;
   String errorMsg;
   JDialog popup;

   public TexFieldValidator(String regex, String errorMsg) {
      this.regex = regex;
      this.errorMsg = errorMsg;
   }

   @Override
   public boolean verify(JComponent input) {
      boolean verified = false;
      String text = ((JTextField) input).getText();
      if (text.matches(regex)) {
         input.setBackground(Color.WHITE);
         if (popup != null) {
            popup.dispose();
            popup = null;
         }
         verified = true;
      } else {
         if (popup == null) {
            popup = new JDialog((Window) input.getTopLevelAncestor());
            input.setBackground(Color.PINK);
            popup.setSize(0, 0);
            popup.setLocationRelativeTo(input);
            Point point = popup.getLocation();
            Dimension dim = input.getSize();
            popup.setLocation(point.x - (int) dim.getWidth() / 2, point.y + (int) dim.getHeight() / 2);
            popup.getContentPane().add(new JLabel(errorMsg));
            popup.setUndecorated(true);
            popup.setFocusableWindowState(false);
            popup.getContentPane().setBackground(Color.PINK);
            popup.pack();
         }
         popup.setVisible(true);
      }

      return verified;
   }
}

Stolen from here .

Example of use:

iDTextField.setInputVerifier(new TexFieldValidator("[a-zA-Z0-9]{3}", "ID must be 3 alphanumerics."));

您可以为此使用DocumentFilter ,也可以使用JFormattedTextField

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM