Java GUI 菜单问题
statCl.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e) {
try {
ta.append("Searching...\n");
//Do Some stuff, call some classes etc
ta.append("Search Complete\n");
} catch (Exception IOE) {}
}
});
这似乎是一个奇怪的问题,但我的 GUI 遇到了一些问题。基本上,我想要它,所以您单击 JMenu,找到您想要的项目,单击它,它就会运行上面的代码。
但是,当您单击按钮时,它会在操作监听器等内部运行进程时冻结。然后它最终会继续,关闭菜单并让用户继续。问题是,程序看起来像是崩溃了。
理想情况下,我希望用户单击,出现文本“搜索...”,该过程运行,然后一旦该过程完成,它会打印出“搜索完成”
我已经尝试将内容移入和移出try/catch,我尝试为同一项目添加一个单独的actionListener,但没有成功
任何想法将不胜感激。
statCl.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e) {
try {
ta.append("Searching...\n");
//Do Some stuff, call some classes etc
ta.append("Search Complete\n");
} catch (Exception IOE) {}
}
});
This might seem like an odd question but I'm having a couple of issues with my GUI. Basically, I want it so you click through the JMenu, get to the item you want, click that and it runs the code above.
However, when you click the button, it sort of freezes whilst it runs the processes inside the actionListener etc. It then eventually continues, closes the menu and lets the user carry on. Problem is, it sort of looks like the program has crashed.
Ideally, I'd like it so the user clicks, the text 'Searching...' appears, the process runs and then once the process is done it prints out 'Search Complete'
I've tried moving things in and out of the try/catch, I've tried adding a separate actionListener for the same item and no luck
Any ideas would be really appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用 SwingWorker。
对用户界面的所有更新都必须发生在事件调度线程 (EDT) 上。操作侦听器内的代码也会在 EDT 上调用。这意味着当您的代码运行时,UI 将不会更新。
处理此问题的正常方法是让长时间运行的代码在 SwingWorker 内运行。 SwingUtilities然后,.invokeLater 可用于让长时间运行的代码调用方法来更新 UI,这必须在 EDT 上发生。
You need to use a SwingWorker.
All updates to the user interface must occur on the Event Dispatch Thread (EDT). The code inside your action listener gets called on the EDT too. Which means that while your code is running, the UI will not update.
The normal way to handle this is to have the long-running code run inside a SwingWorker. SwingUtilities.invokeLater can then be used to let your long-running code call methods to update the UI, which must happen on the EDT.
尝试使用 SwingWorker。
Try using the SwingWorker.