Is there any way to add more than one mask to a Jformattedtextfield?

Asked

Viewed 193 times

2

I have JFormattedTextField for a price attribute'.

In it I say that its format is "R$ #####,##". However, as I do not yet know how to add events (I am learning) I would like right away if it is necessary (and possible) a new mask (and as, if applicable), for example, for values R$ ###,## or R$ ##,##, because the values will not always be in the thousand range, but I would like to have a format, as already indicated.

1 answer

1

@Jnmarcos does not believe that it exists without extender and create your own Formatterfactory. But you can use a simple solution like:

jFormattedTextField.setFocusLostBehavior(JFormattedTextField.PERSIST);

This way when formattedTextField loses focus it will not erase the field value. (This will turn your formattedTextField into a normal jTextField).

You can use a field and deal with a value Listener event:

field.addFocusListener(new Focusadapter() {

        @Override
        public void focusLost(FocusEvent e) {
            jFormattedTextField.addFocusListener(new FocusAdapter() {

                @Override
                public void focusLost(FocusEvent e) {
                    String text = jFormattedTextField.getText();

                    if (!text.isEmpty()) {
                        int indexOf = text.indexOf(",");//index da vírgula, se é -1 é por que não existe.

                        if (indexOf == -1) {//não existe vírgula, então completa-se com ",00"
                            text = text + ",00";

                        } else {

                            String aposVirgula = text.substring(indexOf + 1);

                            int decimais = aposVirgula.length();//obtém o tamanho do texto após a vírgula

                            if (decimais == 0) {//se Zero, é porque o valor está dessa forma "1000,"
                                text = text + "00";//então completa-se com o 2 zeros

                            } else if (decimais == 1) {// se Um então , é porque o valor está dessa forma "1000,0"
                                text = text + "0";//então completa-se com o 1 zero
                            }
                        }

                        try {
//Fazendo isso, note que seu field permite que insira caracteres. Por isso você precisará checar se o valor é um numero válido.
                            Float.valueOf(text.replace(",", "."));
                        } catch (NumberFormatException er) {
                            text = null;
                        }
                        field.setText(text);
                    }
                }
            });

I suggest you use a Document in the Jtextfield instead of this code.

Browser other questions tagged

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