JTextField

2 respostas
L

Tenho 1 campo e texto e gostaria que ele so aceitasse numeros. gostaria tambem que ele so aceitasse 5 digitos e que quando eu inserisse o 5 digito ele automaticamente executasse tab. ou seja mudava para o outro campo.

Alguem me pode dar um exemplo com codigo, supondo que o campo de texto tenha a referencia de “TEXTO1”

Obrigado desde ja!

2 Respostas

Mantu
package customJTextField;

import java.awt.Container;

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class CustomJTextField extends JFrame {
	private JTextField
		TEXTO1,
		txtNome
	;
	
	private StringBuffer errorCauses = null;
	
	public CustomJTextField() {
		instanciateComponents();
		configGUI();
	}

	private void instanciateComponents() {
		TEXTO1 = new JTextField();
		TEXTO1.setBounds(0, 21, 100, 20);
		TEXTO1.setInputVerifier(new MyVerifier());
		
		txtNome = new JTextField();
		txtNome.setBounds(0, 71, 100, 20);
	}

	private void configGUI() {
		Container c = getContentPane();
		c.setLayout(null);
		
		JLabel lblCodigo = new JLabel("Código");
		lblCodigo.setBounds(0, 0, 150, 20);
		c.add(lblCodigo);
		c.add(TEXTO1);
		
		JLabel lblNome = new JLabel("Nome");
		lblNome.setBounds(0, 50, 150, 20);
		c.add(lblNome);
		c.add(txtNome);
		
		setBounds(0, 0, 150, 130);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	}

	public static void main(String[] args) {
		(new CustomJTextField()).show();
	}
	
	private class MyVerifier extends InputVerifier {
		private boolean allowLostOfFocus = false;
		
		/* 
		 * Método implementado
		 */
		public boolean verify(JComponent input) {
			errorCauses = new StringBuffer("");
			
			if(!(input instanceof JTextField)) {
				errorCauses.append(
					"Um objeto MyVerifier só deve ser " +
					"associado a componentes do tipo JTextField"
				);
				return false;
			}
			
			JTextField txt = (JTextField)input;
			if(txt.getText().length() != 5) {
				errorCauses.append("- O campo deve ter 5 digitos.");
			}
			try {
				Integer.parseInt(txt.getText());
			}catch(NumberFormatException e) {
				errorCauses.append(errorCauses.length() == 0 ? "- " : "\n- ");
				errorCauses.append("O campo deve ter apenas numeros.");
			}
			
			return errorCauses.length() == 0;
		}

		/* 
		 * Método sobrescrito
		 */
		public boolean shouldYieldFocus(JComponent input) {
			if(allowLostOfFocus)
				return true;
			if(verify(input))
				return true;
			
			/*
			 *  Trate aqui a entrada inválida da forma que lhe for mais 
			 * conveniente
			 */
			allowLostOfFocus = true;
			JOptionPane.showMessageDialog(
				input.getParent(),
				errorCauses,
				"Erro",
				JOptionPane.ERROR_MESSAGE);
			allowLostOfFocus = false;
			return false;
		}
		
		
	}

}

Espero que isso ajude

I
package yo;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class TesteNumerico extends JFrame{
     
   JTextField tf ;
   
   public TesteNumerico() {
      
      
      super(" Seja bem vindo");
      getContentPane().setLayout(null);
   
      tf = new JTextField();
      tf.setBounds(50,50, 120,20);
      tf.addKeyListener(new KeyListener(){

         public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();
            
              if(!Character.isDigit(c)){
                 e.consume();
              }   
            
         }

         public void keyPressed(KeyEvent e) {
            
            
            
         }

         public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub
            
         }
         
      });
      
      getContentPane().add(tf);
      setSize(250,250);
      setVisible(true);
   }
     
   public static void main(String args[]){
         new TesteNumerico();
   }
     
   
}

-Isso  vc faz so pra entrar dados do tipo numerico !
Criado 8 de abril de 2006
Ultima resposta 10 de abr. de 2006
Respostas 2
Participantes 3