Só números no JTextField

3 respostas
J

Boa tarde,

Alguém sabe como eu faço pra que em um campo JTextField somente seja permitido digitar números e conforme o usuário vai digitando ele já vai formatando o campo? igual os caixas eletronicos de banco!

Obrigado!

3 Respostas

leandrocliqueaqui

E so vc criar uma classe que extenda de JTextField trabalhando com eventos de cada caracter digitado. Pra adiantar pra vc ta ai o codigo prontinho, mais do que testado.

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

import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class JTextFieldNumeros extends JTextField {

private static final long serialVersionUID = 4664034139319825226L;
//Construtor da classe que realizará o teste no evento de liberação da tecla.

public JTextFieldNumeros() {
	addKeyListener(new KeyListener() {
		public void keyReleased(KeyEvent arg0) {
			ValidaNumero();
		}

		public void keyPressed(KeyEvent arg0) {
			// Método utilizado quando ouver tecla pressionada.

		}

		public void keyTyped(KeyEvent arg0) {
			// Método utilizado quando for digitada.
		}

	});
}

//Método chamado no evento para testar o caracter digitado.
private void ValidaNumero() {
	float valor=0;
	if (this.getText().length() != 0) {
		try {
			valor = Float.parseFloat(this.getText());
		} catch (NumberFormatException ex) {
			JOptionPane.showMessageDialog(null,
					"Esse Campo só aceita números", "ATENÇÃO",
					JOptionPane.INFORMATION_MESSAGE);
			this.setText("");
			this.grabFocus();
		}
	}
}

}

Ironlynx
Vc pode usar um Document, tipo:
import javax.swing.text.*;
public class MonetarioDocument extends PlainDocument {

 public static final int NUMERO_DIGITOS_MAXIMO = 12;

 public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {

  String texto = getText(0, getLength());

  for (int i = 0; i < str.length(); i++) {
      char c = str.charAt(i);
      if (!Character.isDigit(c)) {
          return;
      }
  }

   if(texto.length() < this.NUMERO_DIGITOS_MAXIMO){
          super.remove(0, getLength()); 
      texto = texto.replace(".", "").replace(",", "");
      StringBuffer s = new StringBuffer(texto + str);

   if (s.length() > 0 && s.charAt(0) == '0') {
       s.deleteCharAt(0);
   }

   if(s.length() < 3) {
     if (s.length() < 1) { 
         s.insert(0,"000");
     }else if (s.length() < 2) {
         s.insert(0,"00");
   }else{
    s.insert(0,"0");
    }
   } 

  s.insert(s.length()-2, ",");

  if(s.length() > 6) {
    s.insert(s.length()-6, ".");
  }

  if(s.length() > 10) {
    s.insert(s.length()-10, ".");
  }

  super.insertString(0, s.toString(), a);
  }
}

  public void remove(int offset, int length) throws BadLocationException {
    super.remove(offset, length); 
      String texto = getText(0, getLength());
      texto = texto.replace(",", "");
      texto = texto.replace(".", "");
    super.remove(0, getLength());
    insertString(0, texto, null);
  }

}
depois é só chegar no seu JTextField e: seuJTextField.setDocument(new MonetarioDocument());
J

Deu certo!
Obrigado pela ajuda!

Criado 23 de outubro de 2007
Ultima resposta 24 de out. de 2007
Respostas 3
Participantes 3