再会!我想使用具有全屏独占模式的标准摇摆计时器。为此,我应用了 SwingWorker 来控制应设置图形模式的事件。以下所有步骤都在 run 方法中执行。从 main 调用 run()。1)首先,我创建我的 SwingWorker 对象并覆盖它的两个方法(doInBackground 和 done)。Init 是重要的方法,因为它应该将所有需要的图形设置设置为当前 JFrame 对象并将我的关键侦听器对象(称为 screen_list)与它绑定:
...
worker = new SwingWorker<Window, Void>()
{
public Window doInBackground()
{
init();
return gdev.getFullScreenWindow();
}
public void done()
{
try {
disp = get();
}
catch (InterruptedException ignore) {}
catch (java.util.concurrent.ExecutionException e) {
String why = null;
Throwable cause = e.getCause();
if (cause != null) {
why = cause.getMessage();
} else {
why = e.getMessage();
}
System.err.println("Error retrieving file: " + why);
}
}
};
...
2)然后我创建了实现 ActionListener 和 Key Listener 的屏幕侦听器,它在 init() 方法中与 disp 绑定为 KeyListener:
private void init()
{
...
try
{
disp = gdev.getFullScreenWindow();
if(disp != null)
{
gdev.setDisplayMode(use_dm);
disp.createBufferStrategy(2);
disp.setFocusTraversalKeysEnabled(false);
disp.addKeyListener((KeyListener)screen_list);
}
}
catch(IllegalArgumentException ex)
{
}
...
}
3)我创建并初始化我的摇摆定时器并启动它;4)最后我调用执行方法:
public void run(int pause, int delay)
{
...
try
{
screen_list = new ScreenListener();
tm = new Timer(delay, screen_list);
tm.setInitialDelay(pause);
tm.setRepeats(true);
tm.start();
worker.execute();
}
catch(Exception e)
{}
...
}
我编写的类 ScreenListener 实现了 KeyListener 和 ActionListener。在 ActionPerfomed 方法中,我检查了 worker 是否完成了它的工作(init 方法),如果是,我会参考当前显示模式并绘制一些东西:
class ScreenListener implements ActionListener, KeyListener
{
public void actionPerformed(ActionEvent e)
{
if(!worker.isDone())
{
return;
}
else
{
//gdev - GraphicsDevice type
disp = gdev.getFullScreenWindow();
if (disp != null)
{
...
draw(gr);
...
}
}
}
...
}
为什么不处理来自键盘的事件?