请教高手 如何在JTextField中只允许输入数字 其他一概不允许

解决方案 »

  1.   

    用setDocument(Document doc)
    参数可以扩展PlainDocument类,实现insertString方法,
    先对输入的String进行合法性检查,再调用super的insertString方法。
      

  2.   

    另外一种方法方法:使用文档过滤器
    /**
     * A filter that restricts input to digits and a '-' sign.
     */class IntFilter extends DocumentFilter {
    public void insertString(FilterBypass fb, int offset, String string,
    AttributeSet attr) throws BadLocationException {
    StringBuilder builder = new StringBuilder(string);
    for (int i = builder.length() - 1; i >= 0; i--) {
    int cp = builder.codePointAt(i);
    if (!Character.isDigit(cp) && cp != '-') {
    builder.deleteCharAt(i);
    if (Character.isSupplementaryCodePoint(cp)) {
    i--;
    builder.deleteCharAt(i);
    }
    }
    }
    super.insertString(fb, offset, builder.toString(), attr);
    } public void replace(FilterBypass fb, int offset, int length, String string,
    AttributeSet attr) throws BadLocationException {
    if (string != null) {
    StringBuilder builder = new StringBuilder(string);
    for (int i = builder.length() - 1; i >= 0; i--) {
    int cp = builder.codePointAt(i);
    if (!Character.isDigit(cp) && cp != '-') {
    builder.deleteCharAt(i);
    if (Character.isSupplementaryCodePoint(cp)) {
    i--;
    builder.deleteCharAt(i);
    }
    }
    }
    string = builder.toString();
    }
    super.replace(fb, offset, length, string, attr);
    }
    }
      

  3.   

    为什么不选择JFormattedTextField组件?
    示例:
    JFormattedTextField num = new JFormattedTextField();
    MaskFormatter mask = new MaskFormatter();
    mask.setValidCharacters("0123456789");
    mask.setPlaceholderCharacter('*');//掩码
    mask.install(num);
    这多好啊。
      

  4.   

    那就不要用JTextArea了嘛!JTextField