JTextField JFormattedTextField

3 respostas
vfpribeiro

Bom dia ao forum,

Digam-me uma coisa se fizerem o favor, eu quero preencher um JTextField com valores monetários, ou seja:

0.00
10.00
128.12
*.##

sendo * válido para vários numeros e cada # válido para um numero.

Eu já fui ver o que se poderia fazer sei que com o

new JFormattedTextField(new MaskFormatter("#.##")); Dá muito bem para uma casa inteira mas se eu quiser mais?

e já vi

new JFormattedTextField(new DecimalFormat("##.##")); O que me dá vários . tipo 12.34.56

Agradeço desde já uma ajuda

3 Respostas

manolimars

Cara, tem uma classe que eu uso aqui que formata valores monetários, ve se te ajuda:

import javax.swing.text.*;

public class ValoresMonetarios extends PlainDocument
{

 public static final int NUMERO_DIGITOS_MAXIMO = 12;

    @Override
 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);
  }

}

no seu textField voce só precisa setar o documento:

seuJTextField.setDocument(new ValoresMonetarios());

obs.: ele vai sendo formatado na medida que vai digitando

vfpribeiro

Obrigado Manolimars!!!

Nelsonjahn

Legal isso funciona mesmo, mas agora tenho outro problema ao mostrar dados na tabela ele ainda não formata certo e ao mostrar dados clicando na tabela ele não carrega o textfiel dele de origem. alguém tem alguma ajuda a respeito.
Se prescisar posto todo o código pra ver. Thanks

Criado 17 de março de 2011
Ultima resposta 30 de dez. de 2011
Respostas 3
Participantes 3