禁用向JTextField输入一些符号
如何禁用除数字以外的任何符号输入到JTextField
?
选项1)使用JFormattedTextField更改JTextField,如下所示:
try { MaskFormatter mascara = new MaskFormatter("##.##"); JFormattedTextField textField = new JFormattedTextField(mascara); textField.setValue(new Float("12.34")); } catch (Exception e) { ... }
选项2)从键盘捕获用户的输入,如下所示:
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 } } });
答案是JFormattedTextField
。 请参阅我对这个重复问题的回答 :
您可以使用
JFormattedTextField
。 使用NumberFormatter
构造它,它只接受数字。
JFormattedTextField
有一堆可配置选项,可让您决定输入的error handling方式。 我建议查看文档。
只需消耗不是这样的数字的所有字符:
public static void main(String[] args) { JFrame frame = new JFrame("Test"); frame.add(new JTextField() {{ addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { if (!Character.isDigit(e.getKeyChar())) e.consume(); } }); }}); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); frame.setVisible(true); }
如何使用格式化文本字段
amountField = new JFormattedTextField(NumberFormat.getIntegerInstance());
您还可以创建自己的格式进行自定义。
为了更好的用户体验
其他人已经提到使用JFormattedTextField或KeyListeners来防止输入无效数据,但从可用性的角度来看,我觉得开始输入字段并且没有任何反应非常烦人。
为了提供更好的用户体验,您可以允许用户在字段中输入非数字值,但使用validation器向用户提供反馈并禁用提交按钮。
您可以添加一个自定义KeyListener
来拦截击键,并且不会向JTextField
传播无效的击键。
这对我有用。 看一看。
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(); } }