使用文档列表器限制文本字段中的字符

如何使用DocumentListener限制在JTextField输入的字符数?

假设我想最多输入30个字符。 之后,不能输入任何字符。 我使用以下代码:

 public class TextBox extends JTextField{ public TextBox() { super(); init(); } private void init() { TextBoxListener textListener = new TextBoxListener(); getDocument().addDocumentListener(textListener); } private class TextBoxListener implements DocumentListener { public TextBoxListener() { // TODO Auto-generated constructor stub } @Override public void insertUpdate(DocumentEvent e) { //TODO } @Override public void removeUpdate(DocumentEvent e) { //TODO } @Override public void changedUpdate(DocumentEvent e) { //TODO } } } 

您将要使用DocumentFilter来实现此目的。 如果适用,它会过滤文档。

就像是…

 public class SizeFilter extends DocumentFilter { private int maxCharacters; public SizeFilter(int maxChars) { maxCharacters = maxChars; } public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException { if ((fb.getDocument().getLength() + str.length()) <= maxCharacters) super.insertString(fb, offs, str, a); else Toolkit.getDefaultToolkit().beep(); } public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException { if ((fb.getDocument().getLength() + str.length() - length) <= maxCharacters) super.replace(fb, offs, length, str, a); else Toolkit.getDefaultToolkit().beep(); } } 

创建MDP的Weblog