禁用向JTextField输入一些符号 [英] Disable input some symbols to JTextField

查看:147
本文介绍了禁用向JTextField输入一些符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何禁用除数字以外的任何符号的输入 JTextField

How can I disable input of any symbol except digits to JTextField?

推荐答案

选项1)使用JFormattedTextField更改您的JTextField,如下所示:

Option 1) change your JTextField with a JFormattedTextField, like this:

try {
   MaskFormatter mascara = new MaskFormatter("##.##");
   JFormattedTextField textField = new JFormattedTextField(mascara);
   textField.setValue(new Float("12.34"));
} catch (Exception e) {
   ...
}

选项2)从键盘捕获用户的输入,如下所示:

Option 2) capture user's input from keyboard, like this:

JTextField textField = new JTextField(10);
textField.addKeyListener(new KeyAdapter() {
   public void keyTyped(KeyEvent e) {
      char c = e.getKeyChar();
      if ( ((c < '0') || (c > '9')) && (c != KeyEvent.VK_BACK_SPACE)) {
         e.consume();  // ignore event
      }
   }
});

这篇关于禁用向JTextField输入一些符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆