my code


jTextField - Limitador de caracteres
by cristiantarrazo

Limita la cantidad de caracteres de un jTextField

Snippet options

Download: Download snippet as
Copy snippet: For this you need a free my code account.
Embed code : You will find the embed code for this snippet at the end of the page, if you want to embed it into a website or a blog!

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

public class Limitador extends DefaultStyledDocument {

    int caracteresMaximos;

    public Limitador(int caracteresMaximos) {
        this.caracteresMaximos = caracteresMaximos;

    public void insertString(int offs, String str, AttributeSet a)
            throws BadLocationException {
        if (str.indexOf("?") == -1 && str.indexOf("?") == -1 && (getLength() + str.length()) <= caracteresMaximos) {
            super.insertString(offs, str, a);
        } else {

//Modo de uso
//En el constructor de la clase donde se encuentre el jTextField colocar:
Limitador limite = new Limitador(10);
//Donde campoTest es el jTextField

Create a free my code account now.

my code is a free service, which allows you to save and manage code snippes of any kind and programming language. We provide many advantages for your daily work with code-snippets, also for your teamwork. Give it a try!

Find out more and register now

You can customize the height of iFrame-Codes as needed! You can find more infos in our API Reference for iframe Embeds.