【问题标题】:How to reference the class fromasubclass如何从子类中引用类
【发布时间】:2014-06-05 08:20:57
【问题描述】:

我正在努力寻找答案,但我找不到。在java中,当我创建一个子类时,如何引用第一级类?使用“this”访问子类,所以我不能。另一种选择是将参数传递给子类,但我很好奇是否有最简单的方法。

//here there is my other 1st level class implementation, this is a JFrame
btnNewProject.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

            VehicleScreen pp=new VehicleScreen(**here should go the top class reference**);
                //v is a JPanel that I pass to allJframes
                v.setContentPane(pp);
                v.setVisible(true);
        }
    });

【问题讨论】:

  • 试试 super.topVariable
  • 看看super关键字
  • 不清楚你想要达到什么目的......你能试着澄清你的问题吗?
  • 不能“超级删除此令牌的语法错误”。已经尝试过了,问题是我想访问对象的整个引用而不是单个属性(我可以在不需要超级的情况下做到这一点)。我的意思是,我想在子类中访问顶级对象的引用,假设我的顶级类名为 A,所以我想将 A 的引用传递给我的子类 B(新的 ActionListener)。
  • 你想访问v吗?然后设置final

标签: java swing class jframe jpanel


【解决方案1】:
class Foo {
  int x;

  Foo() {
    new Runnable() {
      public void run() {
        Foo.this.x = 1;
      }
    }
  }
}

【讨论】:

    【解决方案2】:

    你有几个选择:

    1. 将匿名类之外的变量设为实例变量:

      public class AnonymousClass extends JFrame {
          private JLabel label;
          ...
      
          public AnonymousClass() {
          ...
              btnOk.addActionListener(new ActionListener() {
      
                  @Override
                  public void actionPerformed(ActionEvent e) {
                      label.setText(textField.getText());
                  }
              });
          ...
          }
      

      您还可以按如下方式访问实例变量:

      AnonymousClass.this.label.setText(textField.getText());
      
    2. 在局部变量上使用final 修饰符:

      public class AnonymousClass extends JFrame {
          ...
      
          public AnonymousClass() {
          final JLabel label = new JLabel("Enter a new message!");
              btnOk.addActionListener(new ActionListener() {
      
                  @Override
                  public void actionPerformed(ActionEvent e) {
                      label.setText(textField.getText());
                  }
              });
          ...
          }
      

      请注意,使用 final modifier will mean you cannot re-assign the variable at a later point in your program.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多