gpt4 book ai didi

java - HelloWorldSWT eclipse 的运行时问题

转载 作者:行者123 更新时间:2023-12-02 00:37:43 25 4
gpt4 key购买 nike

我刚刚下载了 Eclipse,并正在学习 HelloWorldSWT 教程来熟悉 IDE。

程序运行,但与主循环中的 display.sleep() 相反,程序继续占用 CPU 周期。对于本教程来说,这是正常现象吗?我怎样才能防止这种情况发生?

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class HelloWorldSWT {

/**
* @param args
*/
public static void main(String[] args) {

Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Hello world!");
shell.open();
while(!shell.isDisposed()){
display.sleep();
}
display.dispose();
shell.close();
}

}

编辑:我发现

if (!display.readAndDispatch()) {display.sleep();}

解决了问题。但是,我仍然不明白检查不存在的事件然后告诉显示器 sleep 与仅告诉显示器 sleep 会导致此问题之间的区别。

最佳答案

您需要调用display.readAndDispatch()从事件队列中读取事件并对其进行操作(调度)。

甚至必须调度来自 Shell 的 deactivate 事件!

所有基于 SWT 的应用程序都有一个事件循环,就像您添加到帖子中的那样。看看SWT Snippets了解更多示例。

关于java - HelloWorldSWT eclipse 的运行时问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7290398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com