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);
}
}
グローコーダーの推奨により変更されました:
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 コードジェネレーターを使用して最も単純なアプリケーション以上のものを作成する必要がある場合に役立ちます。