简体   繁体   English

限制JTextField的字符数

[英]limit the number of characters of a JTextField

I want to limit the number of characters to be inserted in a JTextField to 10 character. 我想将要插入JTextField的字符数限制为10个字符。 I use a graphical interface under netbeans.thanks. 我在netbeans.thanks下使用图形界面。

To prevent the user from entering more the 10 charaters in a textfield you can use a document. 为了防止用户在文本字段中输入更多的10个字符,可以使用文档。

Create a simple document by extending PlainDocument and to change the behavior override 通过扩展PlainDocument并更改行为替代来创建一个简单的文档

public void insertString(...) throws BadLocationException

This is an example 这是一个例子

public class MaxLengthTextDocument extends PlainDocument {
    //Store maximum characters permitted
    private int maxChars;

    @Override
    public void insertString(int offs, String str, AttributeSet a)
            throws BadLocationException {
        // the length of string that will be created is getLength() + str.length()
        if(str != null && (getLength() + str.length() < maxChars)){
            super.insertString(offs, str, a);
        }
    }

}

After this, only insert your implementation in JTextField , this way: 之后,仅通过以下方式将实现插入JTextField

...
MaxLengthTextDocument maxLength = new MaxLengthTextDocument();
maxLength.setMaxChars(10); 

jTextField.setDocument(maxLength);
...

And that's it! 就是这样!

Best thing is you will get running demo ;) 最好的是,您将获得运行演示;)

class JTextFieldLimit extends PlainDocument {
  private int limit;
  JTextFieldLimit(int limit) {
    super();
    this.limit = limit;
  }

  JTextFieldLimit(int limit, boolean upper) {
    super();
    this.limit = limit;
  }

  public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
    if (str == null)
      return;

    if ((getLength() + str.length()) <= limit) {
      super.insertString(offset, str, attr);
    }
  }
}

public class Main extends JFrame {
  JTextField textfield1;

  JLabel label1;

  public static void main(String[]args){
      new Main().init();
  }
  public void init() {
    setLayout(new FlowLayout());
    label1 = new JLabel("max 10 chars");
    textfield1 = new JTextField(15);
    add(label1);
    add(textfield1);
    textfield1.setDocument(new JTextFieldLimit(10));

    setSize(300,300);
    setVisible(true);
  }
}

Read the section from the Swing tutorial on Implementing a DocumentFilter for a more current solution. 阅读Swing教程中有关实现DocumentFilter的部分,以获取最新的解决方案。

This solution will work an any Document, not just a PlainDocument. 该解决方案将适用于任何文档,而不仅仅是PlainDocument。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM