Real'sHowTo AddThis Feed Button
Custom Search

Limit JTextField input to a maximum lengthTag(s): Swing


public class JTextFieldLimit extends PlainDocument {
  private int limit;
  // optional uppercase conversion
  private boolean toUppercase = false;
  JTextFieldLimit(int limit) {
   this.limit = limit;
  JTextFieldLimit(int limit, boolean upper) {
   this.limit = limit;
   toUppercase = upper;
  public void insertString
    (int offset, String  str, AttributeSet attr)
      throws BadLocationException {
   if (str == null) return;

   if ((getLength() + str.length()) <= limit) {
     if (toUppercase) str = str.toUpperCase();
     super.insertString(offset, str, attr);

import java.awt.*;
import javax.swing.*;

 public class DemoJTextFieldWithLimit extends JApplet{
   JTextField textfield1;
   JLabel label1;

   public void init() {
     getContentPane().setLayout(new FlowLayout());
     label1 = new JLabel("max 10 chars");
     textfield1 = new JTextField(15);
        (new JTextFieldLimit(10));

blog comments powered by Disqus

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2015
[ home ]