Format measurement field with Jformattedtextfield

Asked

Viewed 547 times

-1

I’m trying to create a field to take measurements, I wanted to apply a mask so that it would look like this:

inserir a descrição da imagem aqui

The field already starts with 0.00, then if you type value it keeps formatting.

And when I set back the values in the field, it did not lose the formatting.

I tried some things as it is before : https://stackoverflow.com/questions/14876695/make-jformattedtextfield-accept-decimal-with-more-than-3-digits/14876889#14876889

however the result is different than I expected. I tried to base myself on monetary fields taken from the internet, but also did not succeed.

what I did:

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import static javax.swing.SwingConstants.RIGHT;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.PlainDocument;

public class Main extends JFrame {

    private JPanel jpn = new JPanel();
    private Medida medida = new Medida();

    public Main() {

        jpn.add(medida);
        add(jpn);

        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public static void main(String arg[]) {
        new Main().setVisible(true);
    }
}

class Medida extends JFormattedTextField implements CaretListener {

    public Medida() {

        setColumns(5);
        this.setDocument(new MeuDocument(4));
        setHorizontalAlignment(RIGHT);
        addCaretListener(this);
        setText("0,00");
        getCaret().setDot(getText().length());
    }

    @Override
    public void caretUpdate(CaretEvent e) {
        if (getCaret().getMark() != getText().length()) {
            getCaret().setDot(getText().length());
        }
    }

    public BigDecimal getValor() {
        return new BigDecimal(getText().replace(".", "").replace(",", "."));
    }

    public void setValor(BigDecimal valor) {
        setText(valor.toString());
    }

    class MeuDocument extends PlainDocument {

        private Integer tamanho;

        public MeuDocument(int tamanho) {
            this.tamanho = tamanho + 1; //tem que contar o separador de decimal (,)
        }

        @Override
        public void insertString(int offs, String str, AttributeSet a) {
            try {
                Pattern padrao = Pattern.compile("[0123456789]");
                Matcher matcher = padrao.matcher(str);
                String valorAtual = getText(0, getLength()).trim().replace(".", "").replace(",", "");
                str = str.trim().replace(",", ".");

                /*NumberFormat nf = NumberFormat.getCurrencyInstance();
                String valorFormatado = nf.format(valor).replace("R$ ", "");
                StringBuffer strBuf = new StringBuffer(valorFormatado);

                valorFormatado = valorFormatado.replace(".", "").replace(",", "").replace("-", ""); //retira tudo o que não for dígito para poder verificar o tamanho.

                if ((tamanho != null) && (valorFormatado.length() >= tamanho)) {
                    return;
                }
                super.remove(0, getLength());
                super.insertString(0, strBuf.toString(), a);*/
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
  • I believe that the answer of the duplicate already answers this question, related also to the most alternative, but the first is who really answers.

  • @That’s the question, I need a mask, like leave it in shape when the field starts

  • Just set an initial value with a setText("0.00"), changes practically nothing in the rest.

  • I’ll see what I can do then

  • You came to test as I guided the answer?

Show 1 more comment

1 answer

1

As I mentioned in the comments, this answer already solves the problem by simply adding a setText("0,00"); in the field constructor. The mask will be applied anyway once you start typing something into it.

inserir a descrição da imagem aqui

If you do not want the .(point) as fractional separator and yes the comma, just remove the excerpt below:

DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(getLocale());
otherSymbols.setDecimalSeparator('.');

format.setDecimalFormatSymbols(otherSymbols);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.