Reputation: 105037
When defining nested classes, is it possible to access the "outer" class' methods? I know it's possible to access its attributes, but I can't seem to 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
Upvotes: 4
Views: 2171
Reputation: 10526
There is another trick for using outer-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);
}
}
Upvotes: 3
Reputation: 57707
As your inner class is non-static, all methods of the outer class are automatically visible to the inner class, even private ones.
So, just go ahead and call the method that you want.
For example,
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();
}
});
}
}
For more on this, see the Sun Tutorial on Nested Classes.
Upvotes: 4
Reputation: 3265
Failing everything else you could define a self reference attribute :
MyClass current = this;
and use that..
Though I would also like to know the true, clean, answer to your question!
Upvotes: 0