【发布时间】:2011-05-13 21:42:10
【问题描述】:
美好的一天! 我想使用具有全屏独占模式的标准摇摆计时器。为此,我应用了 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) 我创建并初始化我的 Swing Timer 并启动它; 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);
...
}
}
}
...
}
为什么不处理来自键盘的事件?
【问题讨论】:
-
您不应该从在 doInBackground 中调用的 init 中进行所有 Swing 调用。相反,此方法用于调用必须后台对 Swing 主线程,EDT(因此得名)进行的调用。
-
问题编号 2,您声明:
External class implements a KeyListener but key event processing doesn't work! why???,我想这是您遇到的主要问题以及发布此帖子的原因,但您并没有真正告诉我们有关关键监听器或显示它的任何代码(不是我能看到的),而是发布很多不相关的代码。也许您正在将关键侦听器添加到没有焦点的组件中——我不知道。您可能希望将您的问题简化为基本问题并澄清您的问题。 -
如需尽快获得更好的帮助,请发帖SSCCE。
-
我不会从 init 进行所有这些 Swing 调用。 Init 应该将所有需要的设置设置为当前 JFrame 对象并与它绑定键侦听器:
-
我不会从 init 进行所有这些 Swing 调用。 Init 应该将所有需要的图形设置设置为当前的 JFrame 对象并与它绑定键侦听器。步骤: 1)首先,我创建我的 SwingWorker 对象并覆盖它的两个方法(doInBackground 和 done),从 doInBackground 调用 init; 2)我创建了实现 ActionListener 和 Key Listener 的屏幕监听器; 3)然后我创建并初始化我的 Swing Timer 并启动它; 4)最后我调用执行方法。
标签: java swing timer fullscreen edt