How to limit the number of characters entered in a JTextField
using DocumentListener
?
Suppose I want to enter 30 characters max. After that no characters can be entered into it. I use the following code:
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
}
}
}
You'll want to use a
DocumentFilter
for this purpose. As the applies, it filters documents.Something like...
Create to MDP's Weblog