我有一个实现ActionListener
的类。我的actionPerformed()
方法运行正常。但是,在我的程序开始运行actionPerformed()
之前,我想做一些事情。我可以在boolean
放一个actionPerformed()
,然后就这样运行它,但我正在寻找更清洁的东西。我不能只使用我的构造函数,因为我需要一个完全构造的对象来实现我的目标。有没有办法添加initialize()
或start()
之类的方法,它会在actionPerformed()
开始之前运行?
一些示例代码:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Game implements ActionListener {
public Game() {
// Constructor
}
public void initialize() {
// I want a method of some sort here which is run before the main game
// loop so I can set it up
}
@Override
public void actionPerformed(ActionEvent e) {
// main game runs
}
}
答案 0 :(得分:0)
如果您希望每次创建对象时都进行初始化,则可以使用实例初始化块(IIB)。
和静态初始化块(SIB),如果您希望初始化只发生一次。
所以在你的情况下你想要创建对象但是在构建对象之前。
所以去下面的IIB块
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Game implements ActionListener {
public Game() {
// Constructor
}
{
// I want a method of some sort here which is run before the main game
// loop so I can set it up
}
@Override
public void actionPerformed(ActionEvent e) {
// main game runs
}
}
注意:我删除了初始化的方法签名并使其成为IIB。这将满足您的要求。
当你Game g = new Game();
在构造函数Game()
执行IIB
块执行之前,您将设置为调用actionPerformed()
方法。