Java JTextField set input length via Document model

Description

Java JTextField set input length via Document model

import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class Main extends JFrame {
  public Main() {
    super("JButton");

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new FlowLayout());
    JLabel nameLabel = new JLabel("Name:");
    JTextField name = new JTextField(20);

    getContentPane().add(nameLabel);//from  w ww . ja v  a  2  s .c  o m
    getContentPane().add(name);

    name.setDocument(new LimitedCharDocument());
  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}

class LimitedCharDocument extends PlainDocument {
  private int limit = -1; // < 0 means an unlimited characters

  public LimitedCharDocument() {
    limit = 10;
  }

  public LimitedCharDocument(int limit) {
    this.limit = limit;
  }

  @Override
  public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
    String newString = str;
    if (limit >= 0 && str != null) {
      int currentLength = this.getLength();
      int newTextLength = str.length();
      if (currentLength + newTextLength > limit) {
        newString = str.substring(0, limit - currentLength);
      }
    }

    super.insertString(offset, newString, a);
  }
}



PreviousNext

Related