Java GUI 菜单问题

发布于 2024-10-17 14:14:12 字数 641 浏览 7 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

山田美奈子 2024-10-24 14:14:12

您需要使用 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.

追星践月 2024-10-24 14:14:12

尝试使用 SwingWorker

Try using the SwingWorker.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文