对的,这是可能的。ActionListener
是接口,所以你可以让“main”类实现这个接口,并在Windows类构造函数中将它作为参数传递给Window类。
以下代码片段可以帮助您:
主类:
package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
//button clicked, so do you job here
}
}
窗户类:
package test;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Window extends JPanel
{
public Window(ActionListener listener)
{
JButton b = new JButton("Button 1");
b.addActionListener(listener);
add(b);
//do other stuff
}
public static void main(String[] args)
{
Window w = new Window(new Main());
//continue with initialization process
}
}