有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从AsubClass引用类

我试图找到答案,但我找不到。在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);
        }
    });

共 (2) 个答案

  1. # 1 楼答案

    class Foo {
      int x;
    
      Foo() {
        new Runnable() {
          public void run() {
            Foo.this.x = 1;
          }
        }
      }
    }
    
  2. # 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());
                  }
              });
          ...
          }
      

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