Java Swing GUI

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);
      texte.setDocument(new LimitJTextField(5));

class LimitJTextField extends PlainDocument 
   private int max;
   LimitJTextField(int max) {
      this.max = max;
   public void insertString(int offset, String text, AttributeSet attr) throws BadLocationException {
      if (text == null)
      if ((getLength() + text.length()) <= max) {
         super.insertString(offset, text, attr);


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *