Limit input length of JTextField
package swixml.sample;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class LimitedTextField extends JFrame {
public LimitedTextField() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Limit input length of JTextField");
setLayout(new FlowLayout());
// add a JTextField limit up to 10 chars
add(new JTextField(new LimitedDocument(10), null, 20));
pack();
Dimension sc = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((sc.width - getWidth()) / 2, (sc.height - getHeight()) / 2);
setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new LimitedTextField();
}
}
class LimitedDocument extends PlainDocument {
private int limit;
public LimitedDocument(int limit) {
super();
this.limit = limit;
}
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (limit == 0 || getLength() + str.length() <= limit) {
super.insertString(offs, str, a);
}
}
}