小编典典

如何从匿名类内部访问封闭的类实例变量?

java

如何instance variables从匿名类的方法内部访问?

class Tester extends JFrame {

   private JButton button;
   private JLabel label;
   //..some more

   public Tester() {
        function(); // CALL FUNCTION
   }

   public void function() {
      Runnable r = new Runnable() {
         @Override
         public void run() {
            // How do I access button and label from here ?
         }
      };
      new Thread(r).start();
   }
}

阅读 224

收藏
2020-11-26

共1个答案

小编典典

如何instance variables从匿名类的方法内部访问?

您只需要访问它们即可:

class Tester extends JFrame {

   private JButton button;
   private JLabel label;
   //..some more

   public Tester() {
        function(); // CALL FUNCTION
   }

   public void function() {
      Runnable r = new Runnable() {
         @Override
         public void run() {
            System.out.println("Button's text is: " + button.getText());
         }
      };
      new Thread(r).start();
   }
}

更重要的是:为什么这对您不起作用?

2020-11-26