Return focus to a Jformatedtextfield after clicking button

Asked

Viewed 60 times

1

I need to click on Wipe Button on the Login screen the CPF and Password the cursor goes back to the CPF field.

JFormattedTextField ftUsuario = new JFormattedTextField();
        try {
              MaskFormatter formatter;
              formatter = new MaskFormatter("###.###.###-##");
              formatter.setPlaceholderCharacter('#');
              ftUsuario = new JFormattedTextField(formatter);
        } catch (Exception e1) {
            JOptionPane.showMessageDialog(null, "Informe o seu CPF", "Aviso!", JOptionPane.INFORMATION_MESSAGE);
        }

JButton btnLimpar = new JButton("Limpar");
    btnLimpar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            pfSenha.setText(null);
            ftUsuario.requestFocus(); // AQUI É EXIBIDO O ERRO...
        }
    });
  • And what problem are you facing?

  • ftUsuario.requestFocus(); says: Local Variable ftUsuario defined in an enclosing Scope must be final or effectively final.

  • If it is set with FINAL it gives error in another field...

  • 1

    Then change the field scope to class level. If it is local scope (within the method), to call in anonymous class only if it is final.

  • If I go to 'Expose Component' and set public or Protect the error disappears but even clicking Clear the cursor does not return to the CPF field.

1 answer

3


You are trying to use a variable with local scope (i.e., created within the current method), in a anonymous class, and this is only possible if the variable is declared as final.

Declare the variable as final:

final JFormattedTextField ftUsuario = new JFormattedTextField();

//...

btnLimpar.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        pfSenha.setText(null);
        ftUsuario.requestFocus(); // AQUI É EXIBIDO O ERRO...
    }
});

Or change the scope of your button to class level, example:

public class SuaClasse {

     JFormattedTextField ftUsuario = new JFormattedTextField();

    //...


   private SuaClasse{

       btnLimpar.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            pfSenha.setText(null);
            ftUsuario.requestFocus(); 
         }
      });

    //restante do seu código
}

Here are some references for reading on variable scope:

How to use variables in a location outside the scope where they were created?

What is the difference between scope and lifetime?

  • Outstanding, resolved!

Browser other questions tagged

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