将 JTextField 输入限制为整数 [英] Restricting JTextField input to Integers

查看:34
本文介绍了将 JTextField 输入限制为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题肯定已经被问过和回答了一百万次,但我就是找不到一个简单的解决方案.我有一个 JTextField,它只接受正整数作为输入.我需要一种方法来确保这里没有其他输入.

I know that this question must have been asked and answered a million times, but I just can't find an easy solution. I have a JTextField that is meant to accept only positive integers as input. I need a way to make sure that nothing else gets input here.

我已经有一个 keyListener 附加到这个控件上.删除此侦听器要处理的其他代码,我有这个:

I already have a keyListener attached to this control. Removing the other code that this listener is there to handle, I have this:

       txtAnswer.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {

            int key = e.getKeyCode();

            /* Restrict input to only integers */
            if (key < 96 && key > 105) e.setKeyChar('');
        };
    });

如您所见,我正在尝试使用 KeyCode 来检查刚刚按下的键是否在整数范围内.这似乎有效.但我想要做的是,如果该条目不在此范围内,则简单地忽略该条目.代码 e.setKeyChar('') 旨在处理这个问题,但它不起作用.代码会编译,但没有明显的效果.

As you can see, I'm trying to use the the KeyCode to check whether the key just pressed falls within the range of integers. This seems to work. But what I want to do is to simply disregard the entry if it falls outside of this range. The code e.setKeyChar('') was meant to handle this, but it doesn't work. The code will compile, but it has no visible effect.

谁能告诉我我是否在正确的轨道上?我可以用什么替换 e.setKeyChar('') 来完成这项工作?还是我完全走错了方向?

Can anybody tell me if I am on the right track? What can I replace e.setKeyChar('') with to make this work? Or am I totally going in the wrong direction?

谢谢.

推荐答案

不要为此使用 KeyListener,因为您会错过很多内容,包括粘贴文本.此外,KeyListener 是一种非常低级的构造,因此应该在 Swing 应用程序中避免使用.

Do not use a KeyListener for this as you'll miss much including pasting of text. Also a KeyListener is a very low-level construct and as such, should be avoided in Swing applications.

该解决方案已在 SO 上多次描述:使用 文档过滤器.这个网站上有几个这样的例子,一些是我写的.

The solution has been described many times on SO: Use a DocumentFilter. There are several examples of this on this site, some written by me.

例如:using-documentfilter-filterbypass

还有教程帮助,请查看:实现文档过滤器.

Also for tutorial help, please look at: Implementing a DocumentFilter.

编辑

例如:

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

public class DocFilter {
   public static void main(String[] args) {
      JTextField textField = new JTextField(10);

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

      PlainDocument doc = (PlainDocument) textField.getDocument();
      doc.setDocumentFilter(new MyIntFilter());


      JOptionPane.showMessageDialog(null, panel);
   }
}

class MyIntFilter extends DocumentFilter {
   @Override
   public void insertString(FilterBypass fb, int offset, String string,
         AttributeSet attr) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.insert(offset, string);

      if (test(sb.toString())) {
         super.insertString(fb, offset, string, attr);
      } else {
         // warn the user and don't allow the insert
      }
   }

   private boolean test(String text) {
      try {
         Integer.parseInt(text);
         return true;
      } catch (NumberFormatException e) {
         return false;
      }
   }

   @Override
   public void replace(FilterBypass fb, int offset, int length, String text,
         AttributeSet attrs) throws BadLocationException {

      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.replace(offset, offset + length, text);

      if (test(sb.toString())) {
         super.replace(fb, offset, length, text, attrs);
      } else {
         // warn the user and don't allow the insert
      }

   }

   @Override
   public void remove(FilterBypass fb, int offset, int length)
         throws BadLocationException {
      Document doc = fb.getDocument();
      StringBuilder sb = new StringBuilder();
      sb.append(doc.getText(0, doc.getLength()));
      sb.delete(offset, offset + length);

      if (test(sb.toString())) {
         super.remove(fb, offset, length);
      } else {
         // warn the user and don't allow the insert
      }

   }
}

为什么这很重要?

  • 如果用户使用复制和粘贴将数据插入文本组件会怎样?KeyListener 会错过这个吗?
  • 您似乎想要检查数据是否可以表示整数.如果他们输入了不适合的数字数据怎么办?
  • 如果您想允许用户稍后输入重复数据怎么办?用科学记数法?

这篇关于将 JTextField 输入限制为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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