如何使用JTextField
限制DocumentListener
中输入的字符数?
假设我想最多输入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
}
}
}
答案 0 :(得分:2)
为此,您需要使用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's Weblog