1

我有一个需要几秒钟才能完成的 java 例程。我想加载一个GlassPane(可能带有“预先等待”消息),以防止用户在该例程正在执行时修改 UI,并且在例程完成时自动隐藏。为此,我使用以下代码:

Thread t = new Thread(new Runnable(){
    @Override
    public void run() {
        /*
         * `getPresentation().getFrame()` are methods that return the 
         * Frame which contains my UI
         */
        getPresentation().getFrame().setGlassPane(myGlassPane);
        getPresentation().getFrame().getGlassPane().setVisible(true);
    }
});
t.start();

//this is the routine that takes several seconds to be executed
runCEM();

//hide the GlassPane
getPresentation().getFrame().getGlassPane().setVisible(false);

我设置了一个特定java.awt.CursormyGlassPane. 当我运行上面的代码时,我可以看到新的java.awt.Cursor出现,但不是整个出现GlassPane“请稍候”消息等等......

关于可能导致此问题的任何想法?是否有其他更好的方法来获得我正在寻找的东西而不是使用GlassPaneand Thread

4

1 回答 1

3

Swing 不是线程安全的,因此您已经违反了 Swing 的单线程规则,可能是在两个帐户上。首先,应该在 EDT(事件调度线程)的上下文中显示和隐藏 glassPane。

您的长时间运行的进程应该在 EDT 之外执行。

我能想到的最简单的解决方案是使用SwingWorker. 这提供了许多有用的机制,您可以使用这些机制在另一个线程中执行长时间运行或阻塞的进程,并安全地更新 UI。

查看SwingWorker 线程中的并发以及 SwingWorker了解更多详细信息

于 2016-03-07T10:59:06.203 回答