将ActionListener与其他类中的方法连接起来
问题描述:
所以我有两个类:“Simulator”和“SimulationWindow”。 模拟器保存模拟器使用的所有方法和功能,并定义SimulationWindow的一个实例。将ActionListener与其他类中的方法连接起来
SimulationWindow生成GUI。在这个GUI中我有4个JButton。这些按钮应该调用在Simulator中实现的方法。但是,我怎样才能将按钮连接到监听器?
button1.addActionListener(???);
我挣扎,因为我的程序有一个主类,以启动模拟器:
Simulator sim1 = new Simulator();
所以我有这个对象模拟器并不能创造一个又一个的SimulationWindow?
答
将引用传递到你的模拟器到SimulationWindow的构造函数,并将其保存在一个领域有:
在模拟器:
class Simulator {
private final SimulationWindow window;
public Simulator() {
window = new SimulationWindow(this);
}
...
}
在SimulationWindow:
class SimulationWindow extends JFrame {
private final Simulator sim;
public SimulationWindow(Simulator sim) {
this.sim = sim;
}
...
}
然后你就可以访问sim
在SimulationWindow的实例中以及您在其中添加的ActionListeners中。
为我工作,谢谢! =) – da1m 2014-12-27 13:52:51