Return focus to a JFormatedTextField after clicking button

1

I need to click on the Clear button on the Login screen, the CPF and Password the cursor will return 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...
        }
    });
    
asked by anonymous 06.10.2016 / 19:29

1 answer

3

You are trying to use a locally scoped variable (that is, created within the current method) in an 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, for 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 to read about variable scope:

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

What is the difference between scope and lifetime?

    
06.10.2016 / 19:39