Using methods from the "outer" class in inner classes

When defining nested classes, is it possible to access the methods of the "external" class? I know that you can access its attributes, but I cannot find a way to use its methods.

addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2 && //<-- Here I'd like to } // reference a method }); //from the class where //addMouseListener() is defined! 

thanks

+4
source share
3 answers

Since your inner class is not static, all methods of the outer class are automatically visible to the inner class, even the private one.

So just go ahead and call the method you want.

For instance,

  class MyClass extends JPanel { void doStuff() { } boolean someLogic() { return 1>2; } void setupUI() { addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2 && someLogic()) doStuff(); } }); } } 

See the Sun Tutorial for nested classes for more on this.

+4
source

There is another trick for using external class references in inner classes, which I often use:

 class OuterClass extends JFrame { private boolean methodName() { return true; } public void doStuff() { // uses the local defined method addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { System.out.println(methodName()); // false // localclass method System.out.println(OuterClass.this.methodName()); // true // outerclass method OuterClass.super.addMouseListener(this); // don't run this, btw // uses the outerclasses super defined method } private boolean methodName() { return false; } }); } @Override public void addMouseListener(MouseListener a) { a.mouseClicked(null); } } 
+3
source

Otherwise, you can define the self reference attribute:

MyClass current = this;

and use it.

Although I would also like to know the true, clean answer to your question!

0
source

Source: https://habr.com/ru/post/1309608/


All Articles