Documentação para moeda(JTextField)

7 respostas
V

Galera, é o seguinte, eu tenho uma documentação que permite apenas números inteiros, mas queria que essa documentação aceitasse também virgula, sendo que limitasse o número de decimais, assim como inteiros, tipo o que o delphi faz… alguem tem alguma ideia ? ou tem essa documentação ? Abraços

7 Respostas

panthovillas

este eu encontrei na net, num projeto do Marky Vasconcelos, e dei uma adaptada pra utilizar no netbeans.
segue abaixo:

public class NumberDocument extends PlainDocument {

    private Integer inteiros = 10;

    private Integer decimais = 0;

    private boolean negativo = false;

    private boolean separador = false;

    public NumberDocument() {
        try {
            PropertyDescriptor[] proDes = Introspector.getBeanInfo(getClass()).getPropertyDescriptors();

            for (PropertyDescriptor pd : proDes) {
                pd.setPreferred(pd.getName().equals("inteiros")
                        || pd.getName().equals("decimais")
                        || pd.getName().equals("negativo")
                        || pd.getName().equals("separador"));
            }
        } catch (IntrospectionException ex) {
            Logger.getLogger(SupportDateField.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void insert(String str, AttributeSet a, boolean negativeNumber) throws BadLocationException {
        if (negativo) {
            if (getText(0, 1).equals("-")) {
                if (str.equals("+")) {
                    super.remove(0, 1);
                    return;
                }
            } else {
                if (str.equals("-")) {
                    super.insertString(0, str, a);
                    return;
                }
            }
        } else {
            if (!str.isEmpty() && str.charAt(0) == '-') {
                return;
            }
        }

        str = str.replace("-", "").
                replace(".", "").
                replace(",", "");

        String texto = getText(0, getLength()).
                replace("-", "").
                replace(".", "").
                replace(",", "");

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

        if (texto.length() < (inteiros + decimais)) {
            super.remove(0, getLength());

            StringBuilder s = new StringBuilder(texto).append(str);

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

            int dig = decimais + 1;
            if (s.length() < dig) {
                int i = 1;
                while (true) {
                    if (s.length() > decimais) {
                        break;
                    }

                    if (s.length() < i) {
                        s.insert(0, StringUtils.repeat("0", dig));
                    }

                    i++;
                    dig--;
                }
            }

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

            if (separador) {
                if (s.indexOf(",") > 3) {
                    s.insert(s.indexOf(",") - 3, ".");
                }


                while (true) {
                    if (s.indexOf(".") <= 3) {
                        break;
                    }

                    s.insert(s.indexOf(".") - 3, ".");
                }
            }

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

            if (negativeNumber) {
                super.insertString(0, "-", a);
            }
        }
    }

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        insert(str, a, getText(0, 1).equals("-"));
    }

    @Override
    public void remove(int offset, int length) throws BadLocationException {
        super.remove(offset, length);

        boolean negativeNumber = false;

        if (getText(0, 1).equals("-")) {
            try {
                BigDecimal number = (BigDecimal) TypeUtil.stringToObject(BigDecimal.class, getText(1, getLength()));

                if (number.compareTo(BigDecimal.ZERO) == 1) {
                    negativeNumber = true;
                }
            } catch (Exception ex) {
                Logger.getLogger(NumberDocument.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        String texto = getText(0, getLength());
        texto = texto.replace(",", "").
                replace(".", "").
                replace("-", "");

        super.remove(0, getLength());

        insert(texto, null, negativeNumber);
    }

    public Integer getDecimais() {
        return decimais;
    }

    public void setDecimais(Integer decimais) {
        this.decimais = decimais;
    }

    public Integer getInteiros() {
        return inteiros;
    }

    public void setInteiros(Integer inteiros) {
        this.inteiros = inteiros;
    }

    public boolean isNegativo() {
        return negativo;
    }

    public void setNegativo(boolean negativo) {
        this.negativo = negativo;
    }

    public boolean isSeparador() {
        return separador;
    }

    public void setSeparador(boolean separador) {
        this.separador = separador;
    }

}

espero que sirva.

F

Olá Valeio Bezerra!

Você já usou o JFormattedTextField? Ele atua de forma semelhante ao JTextField, porém permite espeficar a máscara desejada para o campo. Eu criei abaixo um exemplo para você ter uma idéia de como ele funciona:

public class FormattedText {
	
	public static void main(String[] args) throws ParseException {
		
		JFrame frame = new JFrame();
		JPanel panel = new JPanel();
		panel.setLayout(new GridLayout(1,1));
		
		JLabel label = new JLabel("Valor");
		MaskFormatter formatter = new MaskFormatter("###.##");
		JFormattedTextField campoFormatado = new JFormattedTextField(formatter);
		
		panel.add(label);
		panel.add(campoFormatado);
		
		frame.add(panel);
		frame.setSize(150,75);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
}

Essa documentação irá lhe ajudar bastante: http://download.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html#constructors

Abraços!

alchieri

panthovillas usei o código que vc disponibilizou aqui, mais no campo esta jogando dois zeros na frente do valor, e quando negativo remove o caracter - e coloca os dois zeros.

panthovillas

kra, acabei de copiar o codigo daqui e testar e funcionou.
Estranho.

alchieri

kra! Estou achando que é neste trexo aqui:

int dig = decimals+1;
if (s.length() < dig) {
   int i = 1;
	while (true) {
		if (s.length() > decimals) {
			break;
		}
		if (s.length() < i) {
			s.insert(0, StringUtils.repeat("0", dig));
		}
		i++;
		dig--;
	}
}
panthovillas

isso ai é so pra colocar zeros quando o valor for menor q decimais + 1 inteiro

SandroSoftwares

Gente, a solução do Fabricio Vallim é perfeita!
O JFormattedTextField é ideal para isso sem complicações!

Criado 18 de outubro de 2011
Ultima resposta 1 de mar. de 2012
Respostas 7
Participantes 5