Change MaskFormatter in JFormattedTextField

56 views Asked by At

I´m doing a simple log in application on java where the user input is a JFormattedTextField that has a MaskFormatter. What I want to do is where the JFormattedTextField loses focus want to delete the MaskFormatter (because i have a "placeholder") and add the MaskFormatter whenever it has the focus again (so the MaskFormatter only applies when the user is actually in the JFormattedTextField. The only way i´ve found to add the MaskFormatter is via the constructor. Here is some code:

usuario = new JFormattedTextField(new MaskFormatter("########U"));
usuario.addFocusListener(this);
usuario.setBounds(64, 182, 267, 24);
usuario.setBorder(null);
usuario.setText("Introduce tu nombre de usuario");
usuario.setForeground(new Color(204, 204, 204));
usuario.setFont(new Font("Cascadia Code", Font.PLAIN, 11));
contentPane.add(usuario);
@Override
    public void focusGained(FocusEvent e) {
        if (usuario == e.getSource()) {
                        // set MaskFormatter here
            if (usuario.getText().equals("Introduce tu nombre de usuario")) {
                usuario.setText("");
                usuario.setForeground(Color.BLACK);
            }
        }
    }
@Override
    public void focusLost(FocusEvent e) {
        if (usuario == e.getSource()) {
                        // remove MaskFormatter here
            if (usuario.getText().equals("")) {
                usuario.setText("Introduce tu nombre de usuario");
                usuario.setForeground(new Color(204, 204, 204));
            }
        }
    }

i´ve tried to work around with setFormatterFactory method but i dont know how it works, also couldn´t find anything on the internet

1

There are 1 answers

2
camickr On

i have a "placeholder"

Maybe you can use the Text Prompt which was designed to display "prompt text" in a text field when no text has been entered.

The code doesn't work as is with a JFormattedTextField because the formatted text field appears to add spaces to the Document based on the size of the mask.

In the checkForPrompt() method of the above class you can try changing the code to:

//if (document.getLength() > 0)
if (component.getText().trim().length() > 0)

to see if it works the way you want.

Note the Text Prompt class allows you so specify the prompt color so you don't need to change the foreground of the formatted text field.