Limitar um numero de caracteres em JTextField

12 respostas
tuty_xp

Pessoas, preciso de uma grande ajuda, estou trabalhando no meu TCC…tenho que fazer um jogo de palavras cruzadas.
Porém preciso travar os JTextField’s para receberem somente 1 caractere, no caso, uma letra. Como posso fazer isso? Ja tentei usar o JFormattedTextField mas ele não adiantou…só abilitou com numeros, e numeros não preciso ¬¬"
enfim…alguem pode me dar uma luz? e além disso tem minha lógica, mas vamos resolver um problema de cada vez. rs’ :lol:

12 Respostas

tebosoftware

De uma olhada no arquivo que pode ser encontrado aqui no GUJ:

http://www.guj.com.br/articles/29

Falow

Fexx

Vc pode fazer assim:

public void maskLetter(JFormattedTextField jtf) {
		MaskFormatter formatoDois;
		try {
			formatoDois = new MaskFormatter("*");
			formatoDois.setValidCharacters("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
			formatoDois.install(jtf);
		} catch (ParseException e) {
			JOptionPane.showMessageDialog(
					null,
					this,
					"Não foi possivel inserir mask nos campos letras: "
							+ e.getMessage(), 0);
		}
	}

Ai é só passar um JFormattedTextField no parâmetro.

Abraços.

Fica com DEUS.

tuty_xp

tebosoftware:
De uma olhada no arquivo que pode ser encontrado aqui no GUJ:

http://www.guj.com.br/articles/29

Falow

Velho ja vi esse tutorial…mas nao funcionou cara =p

M

Olá… em um exemplo, um form que tenho, como faço:

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

public class CustomerForm extends PlainDocument {

JFrame telaPrincipal = new JFrame("Tela Principal");
public JTextField tf_1, tf_2= null ;

public CustomerForm() {

tf_1 = new JTextField(10);
tf_2 = new JTextField(10);

tf_1.setDocument(new CustomerForm(2));          -->>> aqui limita a qtdade de caracteres no JtextField
tf_2.setDocument(new CustomerForm(2));

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

tf_1.setBounds(175, 34, 44, 20);
tf_2.setBounds(175, 58, 44, 20);

telaPrincipal.add(tf_1);
telaPrincipal.add(tf_2);
}

	public static void main(String[] args) {

		CustomerForm form;

		form = new CustomerForm();
}
}
tebosoftware

O código do tutorial funciona sim eu utilizo ele.
O objecto document é utilizando dentro do Jtextfield para controlar o texto que está sendo digitado e a implementação que está no tutorial trava a quantidade desde que você set ele no Jtextfield é claro.

tuty_xp

Fexx:
Vc pode fazer assim:

public void maskLetter(JFormattedTextField jtf) {
		MaskFormatter formatoDois;
		try {
			formatoDois = new MaskFormatter("*");
			formatoDois.setValidCharacters("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
			formatoDois.install(jtf);
		} catch (ParseException e) {
			JOptionPane.showMessageDialog(
					null,
					this,
					"Não foi possivel inserir mask nos campos letras: "
							+ e.getMessage(), 0);
		}
	}

Ai é só passar um JFormattedTextField no parâmetro.

Abraços.

Fica com DEUS.

Caracas velho! vlw! e Unica diferença do meu pro teu código era que ao invés de usar o ‘*’ eu tava colocando o ‘#’, pois em TODOS exemplos que tinha visto tava assim…mas vlw cara, salvou minha vida! por enquanto…rs’ õ/

tuty_xp

Aah eh só pra constar…o JTextField ta com um espaço sempra quando inicia o form. Tenho que apagar ele pra depois digitar…como posso digitar sem que tenha esse espaço atrapalhando?

ViniGodoy

Veja o código do tutorial implementado e funcionando:

target.lan
try {
 /* String -----------> */ fTxt(nome_da_variavel)= new JFormattedTextField(new MaskFormatter("")); // como argumento, tecle com barra de espaço a quantidade desejada .
                           } catch (ParseException e) {
	         e.printStackTrace();
                                  	}
gqferreira

Solucionou o problema já?

tuty_xp

Não exatamente…não entendi o código do colega ViniGodoy…tbm não entendi o do target.lan.
como coloco esse código…vou colocar meu código aqui pra vc’s terem uma noção :wink:

import java.awt.*;
import javax.swing.JFormattedTextField;  
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter; 
import java.awt.event.*;
import java.text.ParseException;

import javax.swing.*;
import javax.swing.event.*;

public class PalavrasCruzadasLV1 extends JFrame {
    private JButton btnNovoJogo, btnAjuda, btnSair, btnEstatisticas;
    private JLabel lblAnimal1, lblAnimal2, lblAnimal3, lblAnimal4, lblAnimal5, lblImagem, lblJogo, lblTitulo, lblImgAnimal1, lblImgAnimal2, lblImgAnimal3, lblImgAnimal4, lblImgAnimal5;
    private JFormattedTextField txt1, txt2, txt3, txt4, txt5, txt6, txt7, txt8, txt9, txt10, txt11, txt12, txt13, txt14, txt15, txt16, txt17, txt18, txt19, txt20;
    private MaskFormatter ftmtxt1, ftmtxt2, ftmtxt3, ftmtxt4, ftmtxt5, ftmtxt6, ftmtxt7, ftmtxt8, ftmtxt9, ftmtxt10, ftmtxt11, ftmtxt12, ftmtxt13, ftmtxt14, ftmtxt15, ftmtxt16, ftmtxt17, ftmtxt18, ftmtxt19, ftmtxt20; 

    public PalavrasCruzadasLV1() throws ParseException {
        //construtor
    	lblAnimal1 = new JLabel ("Elefante");
        lblAnimal2 = new JLabel ("Gato");
        lblAnimal3 = new JLabel ("Cisne");
        lblAnimal4 = new JLabel ("Boi");
        //lblCor5 = new JLabel ("Branco");
        lblTitulo = new JLabel ("Cruzadinha dos Animais");
       
        btnNovoJogo = new JButton("Novo Jogo");
        btnAjuda = new JButton("Ajuda");
        btnEstatisticas = new JButton("Estatísticas");
        btnSair = new JButton("Sair");

        txt1 = new JFormattedTextField();
        txt2 = new JFormattedTextField();
        txt3 = new JFormattedTextField();
        txt4 = new JFormattedTextField();
        txt5 = new JFormattedTextField();
        txt6 = new JFormattedTextField();
        txt7 = new JFormattedTextField();
        txt8 = new JFormattedTextField();
        txt9 = new JFormattedTextField();
        txt10 = new JFormattedTextField();
        txt11 = new JFormattedTextField();
        txt12 = new JFormattedTextField();
        txt13 = new JFormattedTextField();
        txt14 = new JFormattedTextField();
        txt15 = new JFormattedTextField();
        txt16 = new JFormattedTextField();
        txt17 = new JFormattedTextField();
        txt18 = new JFormattedTextField();
        txt19 = new JFormattedTextField();
        txt20 = new JFormattedTextField();
        
        ftmtxt1 = new MaskFormatter();
        ftmtxt1.setMask("*");
        ftmtxt1.setInvalidCharacters("[telefone removido]");
        ftmtxt1.install(txt1);
        txt1.setColumns(1);
       
        ftmtxt2 = new MaskFormatter();
        ftmtxt2.setMask("*");
        ftmtxt2.setInvalidCharacters("[telefone removido]");
        ftmtxt2.install(txt2);
        txt2.setColumns(1);
        
        ftmtxt3 = new MaskFormatter();
        ftmtxt3.setMask("*");
        ftmtxt3.setInvalidCharacters("[telefone removido]");
        ftmtxt3.install(txt3);
        txt3.setColumns(1);
        
        ftmtxt4 = new MaskFormatter();
        ftmtxt4.setMask("*");
        ftmtxt4.setInvalidCharacters("[telefone removido]");
        ftmtxt4.install(txt4);
        txt4.setColumns(1);
        
        ftmtxt5 = new MaskFormatter();
        ftmtxt5.setMask("*");
        ftmtxt5.setInvalidCharacters("[telefone removido]");
        ftmtxt5.install(txt5);
        txt5.setColumns(1);
        
        ftmtxt6 = new MaskFormatter();
        ftmtxt6.setMask("*");
        ftmtxt6.setInvalidCharacters("[telefone removido]");
        ftmtxt6.install(txt6);
        txt6.setColumns(1);
        
        ftmtxt7 = new MaskFormatter();
        ftmtxt7.setMask("*");
        ftmtxt7.setInvalidCharacters("[telefone removido]");
        ftmtxt7.install(txt7);
        txt7.setColumns(1);
        
        ftmtxt8 = new MaskFormatter();
        ftmtxt8.setMask("*");
        ftmtxt8.setInvalidCharacters("[telefone removido]");
        ftmtxt8.install(txt8);
        txt8.setColumns(1);
        
        ftmtxt9 = new MaskFormatter();
        ftmtxt9.setMask("*");
        ftmtxt9.setInvalidCharacters("[telefone removido]");
        ftmtxt9.install(txt9);
        txt9.setColumns(1);
        
        ftmtxt10 = new MaskFormatter();
        ftmtxt10.setMask("*");
        ftmtxt10.setInvalidCharacters("[telefone removido]");
        ftmtxt10.install(txt10);
        txt10.setColumns(1);
        
        ftmtxt11 = new MaskFormatter();
        ftmtxt11.setMask("*");
        ftmtxt11.setInvalidCharacters("[telefone removido]");
        ftmtxt11.install(txt11);
        txt11.setColumns(1);
        
        ftmtxt12 = new MaskFormatter();
        ftmtxt12.setMask("*");
        ftmtxt12.setInvalidCharacters("[telefone removido]");
        ftmtxt12.install(txt12);
        txt12.setColumns(1);
        
        ftmtxt13 = new MaskFormatter();
        ftmtxt13.setMask("*");
        ftmtxt13.setInvalidCharacters("[telefone removido]");
        ftmtxt13.install(txt13);
        txt13.setColumns(1);
        
        ftmtxt14 = new MaskFormatter();
        ftmtxt14.setMask("*");
        ftmtxt14.setInvalidCharacters("[telefone removido]");
        ftmtxt14.install(txt14);
        txt14.setColumns(1);
        
        ftmtxt15 = new MaskFormatter();
        ftmtxt15.setMask("*");
        ftmtxt15.setInvalidCharacters("[telefone removido]");
        ftmtxt15.install(txt15);
        txt15.setColumns(1);
        
        ftmtxt16 = new MaskFormatter();
        ftmtxt16.setMask("*");
        ftmtxt16.setInvalidCharacters("[telefone removido]");
        ftmtxt16.install(txt16);
        txt16.setColumns(1);
        
        ftmtxt17 = new MaskFormatter();
        ftmtxt17.setMask("*");
        ftmtxt17.setInvalidCharacters("[telefone removido]");
        ftmtxt17.install(txt17);
        txt17.setColumns(1);
        
        ftmtxt18 = new MaskFormatter();
        ftmtxt18.setMask("*");
        ftmtxt18.setInvalidCharacters("[telefone removido]");
        ftmtxt18.install(txt18);
        txt18.setColumns(1);
        
        ftmtxt19 = new MaskFormatter();
        ftmtxt19.setMask("*");
        ftmtxt19.setInvalidCharacters("[telefone removido]");
        ftmtxt19.install(txt19);
        txt19.setColumns(1);
        
        ftmtxt20 = new MaskFormatter();
        ftmtxt20.setMask("*");
        ftmtxt20.setInvalidCharacters("[telefone removido]");
        ftmtxt20.install(txt20);
        txt20.setColumns(1);
        
        //adjust size and set layout
        setPreferredSize (new Dimension (1024, 700));
        setLayout (null);

        //add components
        add (btnSair);
        add (btnAjuda);
        add (btnNovoJogo);
        add (btnEstatisticas);
        add (lblAnimal1);
        add (lblAnimal2);
        add (lblAnimal3);
        add (lblAnimal4);
        add (lblTitulo);
        add (txt1);
        add (txt2);
        add (txt3);
        add (txt4);
        add (txt5);
        add (txt6);
        add (txt7);
        add (txt8);
        add (txt9);
        add (txt10);
        add (txt11);
        add (txt12);
        add (txt13);
        add (txt14);
        add (txt15);
        add (txt16);
        add (txt17);
        add (txt18);
        add (txt19);
        add (txt20);

        //set component bounds (only needed by Absolute Positioning)
        btnSair.setBounds     	(820, 650, 100, 35);
        btnEstatisticas.setBounds(600,650,110,35);
        btnAjuda.setBounds		(350, 650, 100, 35);   
        btnNovoJogo.setBounds  	(100, 650, 100, 35);
        
        
        lblAnimal1.setBounds 		(750, 380, 200, 25);
        lblAnimal1.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,18));
       // lblCor1.setForeground(Color.YELLOW);
        
        lblAnimal2.setBounds 		(750, 420, 200, 25);
        lblAnimal2.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,18));
        //lblCor2.setForeground(Color.BLUE);
        
        lblAnimal3.setBounds 		(750, 460, 200, 25);
        lblAnimal3.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,18));
        //lblCor3.setForeground(Color.GREEN);
        
        lblAnimal4.setBounds 		(750, 500, 200, 25);
        lblAnimal4.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,18));
        //lblCor4.setForeground(Color.RED);
        
        //lblAnimal5.setBounds 		(750, 540, 200, 25);
       // lblAnimal5.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,18));
       // lblAnimal5.setForeground(Color.WHITE);
        
        lblTitulo.setBounds(600,60,300,25);
        lblTitulo.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,18));
        
        //Posição dos JTextField's
        txt1.setBounds(28,50,41,40);
        txt1.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
               
        txt2.setBounds(85,50,41,40);
        txt2.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));

        txt3.setBounds(140,50,41,40);
        txt3.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
		
        txt4.setBounds(195,50,41,40);
        txt4.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
        
        txt5.setBounds(245,50,41,40);
        txt5.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));

        txt6.setBounds(245,105,41,40);
        txt6.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
        
        txt7.setBounds(245,162,41,40);
        txt7.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
        
        txt8.setBounds(247,217,41,40);
        txt8.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
        
        txt9.setBounds(247,265,41,40);
        txt9.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
        
        txt10.setBounds(247,321,41,40);
        txt10.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
        
        txt11.setBounds(247,377,41,40);
        txt11.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
        
        txt12.setBounds(250,431,41,40);
        txt12.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
        
        txt13.setBounds(195,266,41,40);
        txt13.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
        
        txt14.setBounds(300,266,41,40);
        txt14.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
        
        txt15.setBounds(355,266,41,40);
        txt15.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
        
        txt16.setBounds(358,215,41,40);
        txt16.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
        
        txt17.setBounds(358,215,41,40);
        txt17.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
        
        txt18.setBounds(358,315,41,40);
        txt18.setFont(new Font("A.C.M.E. Secret Agent",Font.CENTER_BASELINE,20));
        
        
        lblImgAnimal1 = new JLabel();
	    ImageIcon elefante = new ImageIcon("imagens/elefante.gif");
	    lblImgAnimal1.setIcon(elefante);
	    lblImgAnimal1.setBounds(200,480,160,115);
		this.add(lblImgAnimal1);
        
		lblImgAnimal2 = new JLabel();
	    ImageIcon gato = new ImageIcon("imagens/gato.gif");
	    lblImgAnimal2.setIcon(gato);
	    lblImgAnimal2.setBounds(40,220,160,115);
		this.add(lblImgAnimal2);
		
		lblImgAnimal3 = new JLabel();
	    ImageIcon boi = new ImageIcon("imagens/boi.gif");
	    lblImgAnimal3.setIcon(boi);
	    lblImgAnimal3.setBounds(400,150,160,115);
		this.add(lblImgAnimal3);
		
		lblImgAnimal4 = new JLabel();
	    ImageIcon cisne = new ImageIcon("imagens/cisne.gif");
	    lblImgAnimal4.setIcon(cisne);
	    lblImgAnimal4.setBounds(300,5,160,115);
		this.add(lblImgAnimal4);
		
		/*Imagem do Jogo
        lblJogo = new JLabel();
        ImageIcon jogo = new ImageIcon("imagens/CruzadasLV1.png");
		lblJogo.setIcon(jogo);
		lblJogo.setBounds(10,10,600,500);
		this.add(lblJogo);*/
        
		//Imagem no Jlabel do Fundo		
		lblImagem = new JLabel();
		ImageIcon fundo = new ImageIcon("Palavras Cruzadas.jpg");
		lblImagem.setIcon(fundo);
		lblImagem.setSize(fundo.getIconWidth(),fundo.getIconHeight());
		this.add(lblImagem);
		
		
			
		
		
		//eventos dos botões
		btnSair.addActionListener(
	   	         new ActionListener()
	   	         {
	   	             public void actionPerformed(ActionEvent event)
	   	             {
	   	            	frmSair Sair =new frmSair();
	   	            	Sair.setVisible(true);
	   	       
	   	             
	   	             }
	   	             
	   	        
	   	         
	   	         }
	   	         
		);
		
		btnAjuda.addActionListener(
	   	         new ActionListener()
	   	         {
	   	             public void actionPerformed(ActionEvent event)
	   	             {
	   	            	
	   	            	 
	   	        }});
		
		btnNovoJogo.addActionListener(
	   	         new ActionListener()
	   	         {
	   	             public void actionPerformed(ActionEvent event)
	   	             {
	   	            	
	   	        }});
		
        
    }

   public static void main (String[] args) throws ParseException {
	   
	   PalavrasCruzadasLV1 frame = new PalavrasCruzadasLV1 ();
        //frame.getContentPane().add (new PalavrasCruzadasLV1());
        //frame.pack();
	   frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 
       frame.setUndecorated(true);
       frame.setSize(1024,700);
       frame.setResizable(false);
       frame.setVisible (true);
       frame.setLocationRelativeTo(null);//Centralizar o formulário
        
           
        
     /*  JDesktopPane desktop = new JDesktopPane(){  
            Image im = (new ImageIcon("Palavras Cruzadas.jpg")).getImage();   
            public void paintComponent(Graphics g){          
             g.drawImage(im,0,0,this);            }  
       };*/
       
    }
   
}

Minha duvida é como eu tiro o espaço quando inicia o text, pois tenho que apagar o espaço e depois digitar…

tuty_xp

Ahh consegui ajuda com um colega meu da minha turma, pra tirar o espaço que fica no começo do text, tem que apagar ele pra digitar...segue o cóigo ;) :)

txt1.addFocusListener(new FocusListener() {
			
			public void focusLost(FocusEvent arg0) {
				
				txt1.setCaretPosition(0);
			}
			
			
			public void focusGained(FocusEvent arg0) {
				txt1.setCaretPosition(0);
			}
		});
Criado 23 de março de 2012
Ultima resposta 28 de mar. de 2012
Respostas 12
Participantes 7