1

这段代码确实有效,但我认为它可以用不同的方式编写。我有一个自定义 JDialog 用于显示不确定的进度条。对,我在我的 while 循环中设置了标题、可见性和位置。虽然这可行,但我认为它应该显示在我创建工人的位置下方,但是当我这样做时,它会给我一个非法的类型错误开始。有任何想法吗?谢谢。

SwingWorker worker = new SwingWorker<Void, Void>(){
           //I am thinking this should work, but it doesn't
//              Progress.setTitle("Loading Repository");
//              Progress.setLocationRelativeTo(null);
//              Progress.setVisible(true); 
            @Override
            protected Void doInBackground() throws Exception {
                    while (runLoad.getState() != Thread.State.TERMINATED && !isCancelled()) {
                        try {
                            Progress.setTitle("Loading Repository");
                            Progress.setLocationRelativeTo(null);
                            Progress.setVisible(true);  
                            synchronized (this) {
                                Thread.sleep(2000);
                            }
                        } catch (InterruptedException e) {
                            JOptionPane.showMessageDialog(null,
                                    "Process interrupted: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                    return null;
                }
            @Override
            public void done() {
                SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                     Progress.setVisible(false);
                     Progress.dispose();
                    }
                 });
               }
            };
            worker.execute();
4

1 回答 1

1

您不能将此类语句直接放在类中。它们必须在方法内。这就是如果您取消注释这些语句,代码不会编译的原因。

这些语句根本不应该在工人内部。它们应该在封闭方法中,就在执行工作人员之前。实际上,您希望在后台进程启动之前初始化进度对话框并使其仅可见一次。而您不能在 中这样做doInBackground(),因为对 Swing 组件的每次访问都必须在事件调度线程中完成,而不是在后台线程中完成。

对 的调用也是如此JOptionPane.showMessageDialog():它不应该在doInBackground()方法内部,因为它必须在事件调度线程中完成。它应该在done()方法内部,该方法应该调用get()以查看后台进程是否成功。

而且 done() 中的代码不需要包含在中SwingUtilities.invokeLater(),因为done()在事件调度线程中执行。

最后,您应该尊重 Java 命名约定:变量以小写字母开头。

于 2013-11-27T16:08:51.077 回答