Problems accessing class attributes when creating java-based System action

Asked

Viewed 221 times

0

Well I have a class that extends a JPanel, in that JPanel i add a JButton and use the method addActionListener to set a ActionListener for this one JButton, but when I’m creating the ActionListener I can’t access the attributes of JPanel, follows the code below:

public class MemoriaView extends JPanel {
    private GenericAPI api;
    private JButton salvar;

public MemoriaView(){
    super();
    this.setLayout(new MigLayout());
    this.setSize(500,600);
    this.api = new GenericAPI<MemoriaModel>();
    this.salvar = new JButton("Salvar");
    this.salvar.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent evt){
                        /* Aqui quero pode acessar o this.api porem nao consigo */
        }
    });
}

1 answer

1

To access class attributes MemoriaView you need to use MemoriaView.this.atributo to specify that the this the one you refer to is the one of the most external class. The this in that context is the very ActionListener.

Your code would stand:

public class MemoriaView extends JPanel {
    private GenericAPI api;
    private JButton salvar;

    public MemoriaView(){
        super();
        this.setLayout(new MigLayout());
        this.setSize(500,600);
        this.api = new GenericAPI<MemoriaModel>();
        this.salvar = new JButton("Salvar");
        this.salvar.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                MemoriaView.this.api.metodo();
            }
        });
    }
}

Browser other questions tagged

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