How can we limit the number of characters inside a JTextField in Java?


A JTextFeld is one of the most important components that allow the user to an input text value in a single line format. We can restrict the number of characters that the user can enter into a JTextField can be achieved by using a PlainDocument class.

In the below example, we can implement the logic by using a PlainDocument class, hence we can allow a user to enter a maximum of 10 characters, it doesn't allow if we enter more than 10 characters.

Example

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
class JTextFieldLimit extends PlainDocument {
   private int limit;
   JTextFieldLimit(int limit) {
      super();
      this.limit = limit;
   }
   JTextFieldLimit(int limit, boolean upper) {
      super();
      this.limit = limit;
   }
   public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
      if (str == null)
         return;
      if ((getLength() + str.length()) <= limit) {
         super.insertString(offset, str, attr);
      }
   }
}
public class JTextFieldLimitTest extends JFrame {
   JTextField textfield;
   JLabel label;
   public static void main(String[]args){
      new JTextFieldLimitTest().GUI();
   }
   public void GUI() {
      setLayout(new FlowLayout());
      label = new JLabel("max 10 chars");
      textfield = new JTextField(15);
      add(label);
      add(textfield);
      textfield.setDocument(new JTextFieldLimit(10));
      setSize(350,300);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
}

Output

Updated on: 07-Feb-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements