Here you can find the source of maxLength(JTextComponent textComponent, int length)
public static KeyListener maxLength(JTextComponent textComponent, int length)
//package com.java2s; //License from project: Open Source License import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.text.JTextComponent; public class Main { public static KeyListener maxLength(JTextComponent textComponent, int length) { return new KeyAdapter() { @Override/*from w w w . j av a 2s . c om*/ public void keyTyped(KeyEvent e) { if (textComponent.getText().length() >= length) { e.consume(); textComponent.setText(textComponent.getText().substring(0, length)); } } }; } }