访问容器字段

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

我正在使用NetBeans构建一个小应用程序,我遇到了以下问题; 我的主类叫做mainApp ,正在扩展一个JFrame ,后者又包含一个名为drawingBoardJPanel ,我也会因为各种(和偏离主题)的原因而扩展。

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

如何获取mainApp的引用并在mainApp设置其字段的值?

您可以使用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代码生成器来创建除最简单的应用程序之外的任何内容,它将帮助您。

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

耶依依依注射!

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