您可以使用 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 代码生成器来制作最简单的应用程序之外的任何东西,它将为您提供帮助。