1

我有一个非常愚蠢的问题要问。

我正在使用 NetBeans 构建一个小应用程序,但遇到以下问题;我的主类被调用mainApp并且正在扩展 a JFrame,而后者又包含一个JPanel被调用的类drawingBoard,我也出于各种(和离题的)原因进行了扩展..

核心问题是,在某些时候我需要访问其中一个字段,mainApp但由于 NetBeans 实例化我的主类的方式..(作为匿名类)我无法获得对容器的引用(那是我的 mainApp )。

我可以做些什么来获取mainApp其字段的引用并在其中设置其值drawingBoard

4

3 回答 3

3

如果您正在扩展,您可以控制构造函数。通过将它们添加到构造函数来传递您需要的任何引用(当然,将它们分配给成员变量。)

耶依赖注入!

于 2011-02-23T03:07:31.140 回答
1

Glowcoder 的回答很好。另一种选择是使 mainApp 成为单例(如果它是,从逻辑上讲,单例)

于 2011-02-23T03:10:16.140 回答
1

您可以使用 Window win = SwingUtilities.getWindowAncestor(myComponent); 获取对顶级窗口的引用 并将对顶层窗口最终拥有的任何组件的引用传递给方法调用。如果您的主类也是您的顶级 JFrame(您没有初始化任何其他 JFrame),那么您可以将返回的 Window 转换为您的顶级类类型并调用其公共方法。

例如:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Foo1 {
   public static void main(String[] args) {
      MainApp mainApp = new MainApp();
      mainApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      mainApp.pack();
      mainApp.setLocationRelativeTo(null);
      mainApp.setVisible(true);
   }
}

class MainApp extends JFrame {
   public MainApp() {
      getContentPane().add(new DrawingBoard());
   }

   public void mainAppMethod() {
      System.out.println("This is being called from the Main App");
   }
}

class DrawingBoard extends JPanel {
   public DrawingBoard() {
      JButton button = new JButton("Button");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            MainApp mainApp = (MainApp) SwingUtilities.getWindowAncestor(DrawingBoard.this);
            mainApp.mainAppMethod();
         }
      });
      add(button);
   }
}

由glowcoder的建议更改为:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Foo2 {
   public static void main(String[] args) {
      MainApp2 mainApp = new MainApp2();
      mainApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      mainApp.pack();
      mainApp.setLocationRelativeTo(null);
      mainApp.setVisible(true);
   }
}

class MainApp2 extends JFrame {
   public MainApp2() {
      getContentPane().add(new DrawingBoard2(this));
   }

   public void mainAppMethod() {
      System.out.println("This is being called from the Main App");
   }
}

class DrawingBoard2 extends JPanel {
   private MainApp2 mainApp;

   public DrawingBoard2(final MainApp2 mainApp) {
      this.mainApp = mainApp;
      JButton button = new JButton("Button");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            buttonActonPerformed();
         }
      });
      add(button);
   }

   private void buttonActonPerformed() {
      mainApp.mainAppMethod();

   }
}

另一个建议:因为您正在学习 Swing,所以最好不要使用 NetBeans 为您生成 Swing 代码,而是手动编写 Swing 应用程序。通过这样做并学习教程,您将对 Swing 的工作原理有更深入和更好的理解,并且如果您需要使用 NetBeans 代码生成器来制作最简单的应用程序之外的任何东西,它将为您提供帮助。

于 2011-02-23T03:35:03.673 回答