Não estou conseguindo limitar o número de caracteres(jTextField)

Oi pessoal, sou novo no Guj, estou com uma que não consigo desenrolar, se alguem poder me ajudar vou ficar muito agradecido. Minha dúvida é a seguinte: Segundo o que achei isso seria o mais correto e oque mais daria certo para resolver meu problema, é que minha chamada a classe que limita os caracteres não estar dando certo, alguem?

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JanelaCadastro.java
 *
 * Created on 23/02/2012, 21:52:46
 */
package gui;

import apacote.captura;
import javax.print.attribute.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

/**
 *
 * @author Antunes
 */
public class JanelaCadastro extends javax.swing.JFrame {

    /** Creates new form JanelaCadastro */
    public JanelaCadastro() {
        initComponents();
        
        campoCpf.setDocument(new FixedLengthDocument(5));

 }
  
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

    }// </editor-fold>

    private void campoNomeActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
    }                                         

    private void campoEndereçoActionPerformed(java.awt.event.ActionEvent evt) {                                              
        // TODO add your handling code here:
    }                                             

    private void FeminActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
    }                                     

    private void campoApelidoActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO ad your handling code here:
    }                                            

    private void campoDiaActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void campoMesActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void campoAnoActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void MascActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // TODO add your handling code here:
    }                                    

    private void campoEmailActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    private void campoCelularActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
    }                                            

    private void campoTelefoneActionPerformed(java.awt.event.ActionEvent evt) {                                              
        // TODO add your handling code here:
    }                                             

    private void acionarWebActionPerformed(java.awt.event.ActionEvent evt) {                                           
        new captura(this).setVisible(true);
    }                                          

    private void campoCpfActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here: 
    }                                        

    private void campoCpfKeyReleased(java.awt.event.KeyEvent evt) {                                     
        // TODO add your handling code here:
        campoCpf.setText(campoCpf.getText().replaceAll("[^0-9]", ""));  
    }                                    

    
    private void campoTelefoneKeyReleased(java.awt.event.KeyEvent evt) {                                          
        // TODO add your handling code here:
       // campoTelefone.setText(campoTelefone.getText().replaceAll("[^0-9]", "")); 
    }                                         

    private void campoCelularKeyReleased(java.awt.event.KeyEvent evt) {                                         
        // TODO add your handling code here:
        campoCelular.setText(campoCelular.getText().replaceAll("[^0-9]", "")); 
    }                                        

   public void tranferirFoto(Image imagem){

        ImageIcon icon = new ImageIcon(imagem);
        JLabel label  = new JLabel(icon); 
        label.removeAll();
        label.revalidate();
        jPanel2.removeAll();
        jPanel2.revalidate();
        jPanel2.paint(jPanel2.getGraphics());
        
        jPanel2.setLayout(new BorderLayout());
        jPanel2.add(label, BorderLayout.CENTER);
        jPanel2.revalidate();
        jPanel2.paint(jPanel2.getGraphics());
       
       try {
            ImageIO.write((RenderedImage) imagem, "jpg", new File("C:/Users/Antunes/Desktop/Teste.JPG"));
            JOptionPane.showMessageDialog(null, "Imagem Capturada com Sucesso!");
            
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "não foi possivel encontrar " +
            "o dispositivo para a captura da imagem.");
            e.printStackTrace();
        }
    }

   
public class FixedLengthDocument extends PlainDocument
{
    private int iMaxLength;

    public FixedLengthDocument(int maxlen)
    {
        super();
        iMaxLength = maxlen;
    }

  //  @Override
    public void insertString(int offset, String str, AttributeSet attr)
            throws BadLocationException
    {
        if (str == null)
            return;

        if (iMaxLength <= 0) // aceitara qualquer no. de caracteres
        {
            insertString(offset, str, attr);
            return;
        }

        int ilen = (getLength() + str.length());
        if (ilen <= iMaxLength) // se o comprimento final for menor...
            insertString(offset, str, attr); // ...aceita str
        else
        {
            if (getLength() == iMaxLength)
                return; // nada a fazer
            String newStr = str.substring(0, (iMaxLength - getLength()));

            insertString(offset, newStr, attr);
        }
    }
}
   
   
   
   
   
   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JanelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JanelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JanelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JanelaCadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                
                
                new JanelaCadastro().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JRadioButton Femin;
    private javax.swing.JRadioButton Masc;
    private javax.swing.JButton acionarWeb;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.ButtonGroup buttonGroup3;
    private javax.swing.ButtonGroup buttonGroup4;
    private javax.swing.ButtonGroup buttonGroup5;
    private javax.swing.JTextField campoAno;
    private javax.swing.JTextField campoApelido;
    private javax.swing.JTextField campoCelular;
    private javax.swing.JTextField campoCpf;
    private javax.swing.JTextField campoDia;
    private javax.swing.JTextField campoEmail;
    private javax.swing.JTextField campoEndereço;
    private javax.swing.JTextField campoMes;
    private javax.swing.JTextField campoNome;
    private javax.swing.JTextField campoTelefone;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JLabel labelFoto;
    // End of variables declaration

}

Crie um classe que estenda de PlainDocument e faça com que ela trate o número de caracteres inseridos.
Clique neste link que você terá mais informações.

Abraços, fique com Deus!

[quote=Nicolas Fernandes]Crie um classe que estenda de PlainDocument e faça com que ela trate o número de caracteres inseridos.
Clique neste link que você terá mais informações.

Abraços, fique com Deus![/quote]

OOOpa Nicolas, tudo bem cara? Não tenho muita experiência com java ainda e tenho dificuldade em criar essa classe extendida, poderia modificar isso no meu código? ficaria muito grato! até +. :smiley:

na minha classe visao:



import java.awt.Color;
import java.awt.Font;

import javax.swing.AbstractAction;
import javax.swing.Action;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;

public class CustomerForm extends PlainDocument {

	public JTextField tf_novo = null;
	JFrame telaPrincipal = new JFrame("Tela Principal ");


	public CustomerForm() {
		inicializar();
	}

	public void inicializar() {

		telaPrincipal.setBounds(100, 100, 490, 400);
		telaPrincipal.getContentPane().setBackground(Color.LIGHT_GRAY);

		tf_novo = new JTextField(10);
		tf_novo.setBounds(175, 34, 44, 20);

		tf_novo.setDocument(new CustomerForm(2));

               // o (2)) é o tamanho maximo de caracteres no JtextField

		telaPrincipal.add(tf_novo);
		telaPrincipal.setLayout(null);
		telaPrincipal.setVisible(true);
		telaPrincipal.setResizable(false);
		telaPrincipal.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	}
}

a classe Main :


public class Main {
	
	public static void main(String[] args) {
		
		CustomerForm form;
		
		form =	new CustomerForm();
	}

}