0

At first I am beginner in Java. I have problem with checkstyle error mentioned in thread title.

Consider having similiar code:

public class myClass {
  JButton[] buttons;

      public myClass() {
        this.buttons = new JButton[2];
        //constructor code....

        this.buttons[0].addActionListener( new ActionListener() {
                    public void actionPerformed( ActionEvent e ) {                  
                      firstMethod(0, 1);
                      secondMethod(5, 10);
                    }
                });

      }

      public void firstMethod( int x, int y ) {
        // do something

     }

      public void secondMethod( int x, int y ) {
        // do something

     }

    }

In constructior I've created onclick event for button from attribute buttons, where when the button is clicked it will perform method firstMethod(int, int) and secondMethod(int, int), everything working of course, but the checkstyle throws me the error. For some reasons I cannot just use this.firstMethod() as I am inside another object (ActionListener).

Any ideas how to throw myClass reference into actionListener?

t4dohx
  • 675
  • 4
  • 24
  • Possibly, but checkstyle error is not mentioned in the post you posted so I didnt find solution. – t4dohx Dec 05 '16 at 22:23

2 Answers2

1

Use myClass.this instead of plain this to refer to the outer class instance. Also use uppercase for classes, so MyClass, not myClass.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
1

The new ActionListener() { ... }; block actually creates a new anonymous class. Inside that block, this refers to the ActionListener. To refer to the outer myClass object, use myClass.this.

Sam
  • 8,330
  • 2
  • 26
  • 51