Problems accessing class attributes when creating action listener with java

0

I have a class that extends a JPanel , in this JPanel I add a JButton and I use the addActionListener method to set a ActionListener to that JButton , but when I'm creating ActionListener I can not access the attributes of JPanel , follow 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 */
        }
    });
}
    
asked by anonymous 22.06.2014 / 21:21

1 answer

1

To access the attributes of the MemoriaView class you need to use MemoriaView.this.atributo to specify that the this to which you refer is the outermost class. The this in that context is ActionListener itself.

Your code would look like:

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();
            }
        });
    }
}
    
22.06.2014 / 21:51