Creating field with weight format with two decimal places and 3 houses before the comma

Asked

Viewed 1,020 times

0

I’m trying to create a "weight" field, but I’m having some problems.

The weight can vary from 2 to 3 decimal places before the point. For example, it could be 80.00 Kg or 100.00 Kg. However, the way I’m doing it, it forces me to put the 3 houses before the point.

I also tried to put one setText("00.00"); for the field not to "start" only with the point, but it did not pick up. How can I solve this?

public class Peso extends JFrame {

    public static void main(String[] args) {
        Peso t = new Peso();
        t.setVisible(true);
    }

    CampoPeso peso = new CampoPeso();
    JPanel painel = new JPanel();

    public Peso() {
        JLabel label = new JLabel("Peso:");
        painel.add(label);
        painel.add(peso);
        add(painel);

        setSize(220, 100);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

class CampoPeso extends JFormattedTextField {

    public CampoPeso() {
        setColumns(5);
        setText("00.00");
        try {
            MaskFormatter mf = new MaskFormatter("###.##");
            mf.install(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //para pegar o valor
    public Float getValor() {
        return new Float(getText().replace(".", "").replace(",", "."));
    }

    //setar o valor
    public void setValor(Object valor) {
        setText(valor.toString());
    }
}
  • It’s unclear what you want to solve. What’s the problem with the code?

  • @The mask always forces me to put the 3 houses

  • @Articuno is that I do not know how it leaves "dynamic",if I put 2, only goes up to 99kg for example.

  • If the goal is to limit the maximum size and not set a fixed size, then the answer of this duplicate solves the problem.

  • the more I can use with the mask ? I wanted to create the field in a way that it is separate, entede ? 85.00 for example, in that answer will only limit the amount

  • @I understand, complicated, I’m still a beginner, I believe I can not make one in the hand yet. I’ll see which one is better then between the options there.

  • Has a mask in decimal format, maybe it fits. I just do not know if it forces all fields, I need to test here.

Show 2 more comments

1 answer

3


As a solution of this reply in Soen, you can customize the mask this way:

public CampoPeso() {
    setColumns(5);

    setFormatterFactory(new AbstractFormatterFactory() {

        @Override
        public AbstractFormatter getFormatter(JFormattedTextField tf) {
            DecimalFormat format = new DecimalFormat();
            format.setMinimumFractionDigits(2);
            format.setMaximumFractionDigits(2);
            format.setRoundingMode(RoundingMode.HALF_UP);
            NumberFormatter formatter = new NumberFormatter(format);
            formatter.setAllowsInvalid(false);
            formatter.setMinimum(0.00);
            formatter.setMaximum(999.99);
            return formatter;
        }

    });

}

Briefly explaining, I am creating a decimal numerical mask, which limits to two fractional houses, values between 0,00 to 999,99.

Working:

inserir a descrição da imagem aqui


Making a small change, as per this other reply from Soen, it is also possible to force "."(dot) as default decimal separator:

class CampoPeso extends JFormattedTextField {

    public CampoPeso() {
        setColumns(5);

        setFormatterFactory(new AbstractFormatterFactory() {

            @Override
            public AbstractFormatter getFormatter(JFormattedTextField tf) {
                DecimalFormat format = new DecimalFormat();
                format.setMinimumFractionDigits(2);
                format.setMaximumFractionDigits(2);
                format.setRoundingMode(RoundingMode.HALF_UP);

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

                format.setDecimalFormatSymbols(otherSymbols);
                NumberFormatter formatter = new NumberFormatter(format);
                formatter.setAllowsInvalid(false);
                formatter.setMinimum(0.00);
                formatter.setMaximum(999.99);
                return formatter;
            }

        });

    }

    // para pegar o valor
    public Float getValor() {
        return Float.valueOf(getText());
    }

   (...)

}

Note that you need to change your method getValor(), because now that the number already comes with point as separator, no more need to replace comma by point.

  • 1

    thank you very much !

  • where you defined that he should assign comma?

  • @Javinha The combination of DecimalFormat + NumberFormatter defines that it must be a fractional number separated by comma.

  • and how do I change to a point ? Because when I take this value as a float,.

  • @Javinha your code no longer does that, swap comma for point? I think you’re starting to complicate something that is already a little complicated.

  • he does not exchange. I tried to let the replace there, as I saw in a reply his, but n has how to type in the field

  • @Javinha as no? In GIF I am using exactly your code. The only modification is the one that I added in the reply and allowed me to type normal.

  • @Javinha tries to adapt from this link response, if he can’t, warns me that later I try to modify the answer, now I’m on the phone and it gets a little complicated to edit. https://stackoverflow.com/a/5054217/5524514

  • Decimalformat df = new Decimalformat(formatString, otherSymbols); formatString, otherSymbols what I pass here?

  • @Javinha updated.

Show 5 more comments

Browser other questions tagged

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