How To Limit the Number of Characters in JTextField
In this tutorial, we are going to see how To limit the number of characters in JTextField. JTextField is one of the most important components that allow the user to enter a text value in a single line. We can limit the number of characters the user can enter in a JTextField by using PlainDocument class.
In the example below, we can implement the logic using PlainDocument class, so we can allow a user to enter a maximum of 5 characters.
Java Program To Limit the Number of Characters in JTextField:
import java.awt.*; import javax.swing.*; import javax.swing.text.*; public class Limit5Char extends JFrame { public static void main(String[]args){ new Limit5Char().initComponent(); } public void initComponent() { setLayout(new FlowLayout()); JLabel lbl = new JLabel("Enter text: "); JTextField texte = new JTextField(15); add(lbl); add(texte); texte.setDocument(new LimitJTextField(5)); setSize(300,70); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } } class LimitJTextField extends PlainDocument { private int max; LimitJTextField(int max) { super(); this.max = max; } public void insertString(int offset, String text, AttributeSet attr) throws BadLocationException { if (text == null) return; if ((getLength() + text.length()) <= max) { super.insertString(offset, text, attr); } } }
Output: