输入文本只接受数字 [英] Input text only accepts numbers

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

问题描述

我设计了一个带有一些JTextFields的小摆动GUI,但是它有一个validateVariables方法,它必须验证接口内的所有字段,有一个JTextField调用(IP)必须只接受int变量我该如何设置它这样吗?

I desinged a little swing GUI that has some JTextFields, but it has a validateVariables method that has to validate all the fields that are inside the interface, there's one JTextField called (IP) must accept only int Variables how can i set it up like that?

PS JTextfield是用nette工具创建的。

P.S the JTextfield was created it in netbeans with the palete tool.

推荐答案

这是JTextField的javadoc
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html

This is the javadoc of JTextField http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html

有示例

public class UpperCaseField extends JTextField {

  public UpperCaseField(int cols) {
    super(cols);
  }

  protected Document createDefaultModel() {
    return new UpperCaseDocument();
  }

  static class UpperCaseDocument extends PlainDocument {

    public void insertString(int offs, String str, AttributeSet a)
      throws BadLocationException {

        if (str == null) {
          return;
        }
        char[] upper = str.toCharArray();
        for (int i = 0; i < upper.length; i++) {
          upper[i] = Character.toUpperCase(upper[i]);
        }
        super.insertString(offs, new String(upper), a);
      }
    }
  }

此示例更改所有用户输入大写。
只需修改insertString方法,删除所有非数字字符,
即可使文本字段仅接受数字。

This example changes all user input to upper case. Just modify the insertString method, remove all non-digit characters, you can make your text field accept digits only.

示例:

public void insertString(int offs, String str, AttributeSet a)
    throws BadLocationException {
  if (str == null) {
    return;
  }
  super.insertString(offs, str.replaceAll("[^0-9]", ""), a);
}

----编辑----

---- EDIT ----

正如@MadProgrammer所说,DocumentFilter是另一种方法,例如:

As @MadProgrammer said, DocumentFilter is another way to do so, for example:

Document document = someJTextField.getDocument();
if (document instanceof AbstractDocument) {
  ((AbstractDocument) doc).setDocumentFilter(new DocumentFilter() {
    public void insertString(DocumentFilter.FilterBypass fb, int offset,  
        String str, AttributeSet a) throws BadLocationException {  
      fb.insertString(offset, str.replaceAll("[^0-9]", ""), a);  
    }
  });
}

这篇关于输入文本只接受数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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