简体   繁体   English

使用内部类中“外部”类的方法

[英]Using methods from the “outer” class in inner classes

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 谢谢

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 . 有关详细信息,请参阅嵌套类Sun教程

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);
    }

 }

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! 虽然我也想知道真实,干净,回答你的问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM