Limitar jtextField NetBeans

6 respostas
Z
Olá amigos, como que eu poderia fazer um texfield no netbeans so aceita numero e de no maximo 4 caracteres? Codigo Fonte Netbeans
/*
 * limita.java
 *
 * Created on 28 de Junho de 2007, 12:30
 */

package testes;

/**
 *
 * @author  gggg
 */import java.util.Random;
import java.util.Map.Entry;
public class limita extends javax.swing.JFrame {
    
    /** Creates new form limita */
    public limita() {
        initComponents();
    }
    
    /** 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.
     */
    // <editor-fold defaultstate="collapsed" desc=" Cdigo Gerado ">                          
    private void initComponents() {
        codigo = new javax.swing.JTextField();
        codigo.setDocument(new FixedLengthDocument(10)); 

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(159, 159, 159)
                .add(codigo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 173, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(68, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(90, 90, 90)
                .add(codigo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(190, Short.MAX_VALUE))
        );
        pack();
    }// </editor-fold>                        
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new limita().setVisible(true);
            }
        });
    }
    
    // Declarao de variveis - no modifique                     
    private javax.swing.JTextField codigo;
    // Fim da declarao de variveis                   
    
}
COdigo que eu copiei aqui no GUJ
/* FixedLengthDocument.java */

import javax.swing.*;
import javax.swing.text.*;

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
        {
            super.insertString(offset, str, attr);
            return;
        }

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

            super.insertString(offset, newStr, attr);
        }
    }
}

6 Respostas

S

Amigo, zzzhhh, você pode tentar adicionar um KeyListener, capturar o evento keyPressed(KeyEvent ke) e, logo em seguida, usar o método subtring(0, 4). Sendo assim, limitará a entrada na caixa de texto em quatro caracteres. Para saber quantos caracteres existem na JTextFild você pode usar o método length(). Quanto aos códigos, tente desenvolvê-los.

B

Olá…
Também fiz no NetBeans…

private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {                                     
        // TODO adicione seu código de manipulação aqui:
        
        int k = evt.getKeyChar();
        if((k > 47 && k < 58)) {
            if(jTextField1.getText().length() == 3){ //quando tiver 4 digitos vai mudar o foco
                jTextField2.requestFocus();
            }
        } else {
            evt.setKeyChar((char)KeyEvent.VK_CLEAR);
        }

    }

testa ai e vê se serve para você!

Até…

Z

obrigado pelas dicas…
amigo BrunoLaser
funcionou blz esse exemplo que vc me passou mas nao ficou bloqueando nenhum caracter
o que pode ser?
valeu

P

Se você já copiou a classe: FixedLengthDocument do artigo aqui do guj, era só ler o artigo até entender.

No constructor da classe que contem o JTextField, basta fazer:

private final static int N = 5;//aqui seria sua constante de definição do tamanho do tf. seuTextField.setDocument(new FixedLengthDocument(N));

Abçs

B
zzzhhh:
obrigado pelas dicas... amigo BrunoLaser funcionou blz esse exemplo que vc me passou mas nao ficou bloqueando nenhum caracter o que pode ser? valeu

Testei este abaixo e está funcionando...

private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {                                     
        // TODO adicione seu código de manipulação aqui:
        
         int k = evt.getKeyChar();
         if((k > 47 && k < 58)) {
             if(jTextField1.getText().length() == 4){
                 evt.setKeyChar((char)KeyEvent.VK_CLEAR);
             }
         } else {
             evt.setKeyChar((char)KeyEvent.VK_CLEAR);
         }
        
    }
R

Boa tarde.

Como implemento este codigo acima no netbeans em um jtextfield?

grato

Criado 28 de junho de 2007
Ultima resposta 21 de mar. de 2011
Respostas 6
Participantes 5