本文介绍了摆动:如何从AWT线程运行作业,但在窗口布局之后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的完整的GUI在AWT线程内运行,因为我使用 SwingUtilities.invokeAndWait(...)启动主窗口。



现在我有一个JDialog,它刚刚显示一个 JLabel ,这表示某个作业正在进行,并且在作业之后关闭该对话框完成。



问题是:标签不显示。这个工作似乎是在 JDialog 被完全铺设之前开始的。



当我只是让对话框打开而不等待作业和关闭,标签 显示。



对话框在其ctor中的最后一件事是 setVisible(true)

诸如 revalidate()重绘(),...也没有帮助。



即使我为受监视的作业启动了一个线程,并等待使用 someThread.join()它没有帮助,因为当前线程(这是AWT线程)被加入,我猜。

替换 JDialog JFrame 也没有帮助。



那么概念是错误的吗?或者我可以在之后进行某些工作,以确保 JDialog (或 JFrame



我要实现的简化算法:




  • 创建 JDialog的子类

  • 确保其及其内容完全展开 - 出来

  • 启动一个进程,等待完成(线程或不行,无关紧要)

  • 关闭对话框



我设法写了一个可重复的测试用例:



EDIT 现在解决了一个答案的问题:
此用例 显示标签,但是在模拟过程之后无法关闭
,因为对话框的形式。

  import java.awt。*; 
import javax.swing。*;

public class _DialogTest2 {
public static void main(String [] args)throws异常{
SwingUtilities.invokeAndWait(new Runnable(){
final JLabel jLabel = new JLabel(Please wait ...);
@Override
public void run(){
JFrame myFrame = new JFrame(Main frame);
myFrame。 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(750,500);
myFrame.setLocationRelativeTo(null);
myFrame.setVisible(true);

JDialog d = new JDialog(myFrame,I'm waiting);
d.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);

d.add(jLabel);
d.setSize(300,200);
d.setLocationRelativeTo(null);
d.setVisible(true);

SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
try {
Thread.sleep(3000); // simulate process
jLabel.setText(Done);
} catch(InterruptedException ex){
}
}
});

d.setVisible(false);
d.dispose();

myFrame.setVisible(false);
myFrame.dispose();
}
});
}
}


解决方案

尝试这个:

  package javaapplication3; 

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Main {

public static void main(String [] args)
throws异常{
SwingUtilities.invokeAndWait(new Runnable()

final JLabel jLabel = new JLabel(Please wait ...);

@Override
public void run(){
JFrame myFrame = new JFrame(Main frame);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(750,500);
myFrame.setLocationRelativeTo(null);
myFrame.setVisible(true);

JDialog d = new JDialog(myFrame,我在等待);

d.add(jLabel);
d.setSize(300,200);
d.setLocationRelativeTo(null);
d.setVisible(true);

new Thread(new Runnable(){

@Override
public void run(){

public void run(){
尝试{
Thread.sleep(3000); // simulate process
jLabel.setText(Done); // HERE:应该在EDT上完成!
} catch(InterruptedException ex){
}
}
})。start();


}
});
}
}

这一个工作,但它是不正确的。我会解释发生了什么。



您的 main()方法以'main'线程开头。所有与Swing相关的代码都应该在EDT线程上完成。这就是为什么你正在使用(正确) SwingUtilities.invokeAndWait(...)。到目前为止这么好。



但是EDT上应该没有长时间运行的任务。由于Swing是单线程,任何长时间运行的进程将阻止EDT。所以你的代码 Thread.wait(...)不应该在EDT上执行。这是我的修改。我将调用包在另一个线程中。所以这是Swing的惯用长时间运行的任务处理。我使用Thread类简洁,但我真的建议使用 SwingWorker 线程。



非常重要:我在前面的例子中犯了一个错误。看到HERE评论的行?这是另一个Swing单线规则违规。线程内的代码正在 EDT之外运行,所以它不应该触摸Swing。所以这个代码是不正确的与Swing一线规则。这不是冻结GUI的安全。



如何纠正?简单。你应该把你的呼叫换成另一个线程,并把它放在EDT队列中。所以正确的代码应该如下所示:

  SwingUtilities.invokeLater(new Runnable(){

public void run(){
jLabel.setText(Done);
}
});

编辑:这个问题触动了很多Swing相关的问题。不能一次解释它们...但是这里还有一个代码片段,这样做是你想要的:

  public static void main(String [] args)
throws异常{
SwingUtilities.invokeAndWait(new Runnable(){

final JFrame myFrame = new JFrame(Main frame);
final JLabel jLabel = new JLabel(Please wait ...);
final JDialog d = new JDialog(myFrame,I'm waiting);

@Override
public void run(){
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(750,500);
myFrame.setLocationRelativeTo(null);
myFrame.setVisible(true);

d.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);

d.add(jLabel);
d.setSize 300,200);
d.setLocationRelativeTo(null);
new Thread(new Runnable(){

@Override
public void run(){
try {
Thread.sleep(3000); // simulate process
System.out.println(After);
SwingUtilities.invokeLater(new Runnable(){

public void run(){


d.setVisible(false);
d.dispose();

myFrame.setVisible(false);
myFrame.dispose();
}
});
} catch(InterruptedException ex){
}
}
})。start();
d.setVisible(true);

}
});
}

总结:




  • 所有Swing相关代码必须在EDT上运行

  • 所有长时间运行的代码不得在EDT上运行

  • 代码可以使用 SwingUtilities在EDT上运行。 ...

    • invokeAndWait() - 正如名称所示,调用是同步的,

    • invokeLater() - 调用代码有时,但立即返回


  • 如果你在EDT上,想要在另一个线程上调用代码,你可以:

    • 创建一个新的线程(将Runnable传递给新主题或覆盖它的 start()方法)并启动它,

    • 创建一个新的 SwingWorker 线程,其中有一些附加功能。

    • 可能使用任何其他线程机制(例如Executor线程)。




典型的GUI方案包括:


  1. 创建GUI组件

  2. 连接属性更改侦听器

  3. 执行与用户操作相关的代码(即运行属性更改侦听器),

  4. 运行可能耗时的任务

  5. 更新GUI状态

1。,2.,3.和4.运行于 EDT 。不应该。编写正确的线程代码有很多种方法。最麻烦的是使用Java早期版本的 Thread 类。如果天真地做到这一点,可以浪费资源(太多的线程一次性运行)。更新GUI也是麻烦的。使用SwingWorker减轻了一些问题。在启动,运​​行和更新GUI(每个都有一个专用的方法,您可以覆盖,并确保它运行在适当的线程),它保证正常运行。


My complete GUI runs inside the AWT thread, because I start the main window using SwingUtilities.invokeAndWait(...).

Now I have a JDialog which has just to display a JLabel, which indicates that a certain job is in progress, and close that dialog after the job was finished.

The problem is: the label is not displayed. That job seems to be started before JDialog was fully layed-out.

When I just let the dialog open without waiting for a job and closing, the label is displayed.

The last thing the dialog does in its ctor is setVisible(true).
Things such as revalidate(), repaint(), ... don't help either.

Even when I start a thread for the monitored job, and wait for it using someThread.join() it doesn't help, because the current thread (which is the AWT thread) is blocked by join, I guess.

Replacing JDialog with JFrame doesn't help either.

So, is the concept wrong in general? Or can I manage it to do certain job after it is ensured that a JDialog (or JFrame) is fully layed-out?

Simplified algorithm of what I'm trying to achieve:

  • Create a subclass of JDialog
  • Ensure that it and its contents are fully layed-out
  • Start a process and wait for it to finish (threaded or not, doesn't matter)
  • Close the dialog

I managed to write a reproducible test case:

EDIT Problem from an answer is now addressed:This use case does display the label, but it fails to closeafter the "simulated process", because of dialog's modality.

import java.awt.*;
import javax.swing.*;

public class _DialogTest2 {
    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeAndWait(new Runnable() {
            final JLabel jLabel = new JLabel("Please wait...");
            @Override
            public void run() {
                JFrame myFrame = new JFrame("Main frame");
                myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                myFrame.setSize(750, 500);
                myFrame.setLocationRelativeTo(null);
                myFrame.setVisible(true);

                JDialog d = new JDialog(myFrame, "I'm waiting");
                d.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);

                d.add(jLabel);
                d.setSize(300, 200);
                d.setLocationRelativeTo(null);
                d.setVisible(true);

                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(3000); // simulate process
                            jLabel.setText("Done");
                        } catch (InterruptedException ex) {
                        }
                    }
                });

                d.setVisible(false);
                d.dispose();

                myFrame.setVisible(false);
                myFrame.dispose();
            }
        });
    }
}
解决方案

Try this:

package javaapplication3;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Main {

public static void main(String[] args)
        throws Exception {
    SwingUtilities.invokeAndWait(new Runnable() {

        final JLabel jLabel = new JLabel("Please wait...");

        @Override
        public void run() {
            JFrame myFrame = new JFrame("Main frame");
            myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            myFrame.setSize(750, 500);
            myFrame.setLocationRelativeTo(null);
            myFrame.setVisible(true);

            JDialog d = new JDialog(myFrame, "I'm waiting");

            d.add(jLabel);
            d.setSize(300, 200);
            d.setLocationRelativeTo(null);
            d.setVisible(true);

            new Thread(new Runnable() {

                @Override
                public void run() {

                public void run() {
                    try {
                        Thread.sleep(3000); // simulate process
                        jLabel.setText("Done");   // HERE: should be done on EDT!
                    } catch (InterruptedException ex) {
                    }
                }
            }).start();


        }
    });
}
}

This one works, but it's not correct. I'll explain whats going on.

Your main() method starts out in 'main' thread. All Swing related code should be done on EDT thread. And this is why You are using (correctly) SwingUtilities.invokeAndWait(...). So far so good.

But there should be no long running tasks on EDT. Since Swing is single threaded any long running processes will block the EDT. So your code Thread.wait(...) should never be executed on EDT. And this is my modification. I wrapped the invocation in another thread. So this is idiomatic long running task handling for Swing. I used Thread class for brevity, but I'd really recommend going with SwingWorker thread.

And very important: I'm making one error in preceding example. See the line with "HERE" comment? This is another Swing one-thread rule violation. Code inside the thread is running outside EDT, so it should never touch Swing. So this code is not a correct with Swing one-thread rule. It's not safe from freezing GUI.

How to correct this? Simple. You should wrap your call in another thread and put it on EDT queue. So correct code should look like:

    SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                jLabel.setText("Done");
            }
        });

EDIT: This question is touching a lot Swing related issues. Can't explain them all at once... But here is one more snippet, which does what You want:

public static void main(String[] args)
        throws Exception {
    SwingUtilities.invokeAndWait(new Runnable() {

        final JFrame myFrame = new JFrame("Main frame");
        final JLabel jLabel = new JLabel("Please wait...");
        final JDialog d = new JDialog(myFrame, "I'm waiting");

        @Override
        public void run() {
            myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            myFrame.setSize(750, 500);
            myFrame.setLocationRelativeTo(null);
            myFrame.setVisible(true);

            d.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);

            d.add(jLabel);
            d.setSize(300, 200);
            d.setLocationRelativeTo(null);
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        Thread.sleep(3000); // simulate process
                        System.out.println("After");
                        SwingUtilities.invokeLater(new Runnable() {

                            public void run() {


                                d.setVisible(false);
                                d.dispose();

                                myFrame.setVisible(false);
                                myFrame.dispose();
                            }
                        });
                    } catch (InterruptedException ex) {
                    }
                }
            }).start();
            d.setVisible(true);

        }
    });
}

To sum up:

  • All Swing related code must run on EDT
  • All long running code must not run on EDT
  • Code can be run on EDT using SwingUtilities....
    • invokeAndWait() - as the name says, call is synchronous,
    • invokeLater() - invoke the code 'sometime', but return immediately
  • If you are on EDT and want to invoke code on another thread, than you can:
    • Create a new Thread (pass a Runnable to new Thread or override it's start() method) and start it ,
    • Create a new SwingWorker thread which has some extras.
    • Possibly use any other threading mechanism (for example Executor threads).

The typical GUI scenario involves:

  1. Creating GUI components,
  2. Wiring up property change listeners,
  3. Executing code related to user actions (i.e. running property change listeners),
  4. Running possibly time consuming tasks,
  5. Updating GUI state,

1., 2., 3. and 4. run on EDT. 4. should not. There are many ways to write proper threading code. The most cumbersome is using Thread class which came with early versions of Java. If one does it naively, resources can be wasted (too many threads runnning at once). Also updating GUI is cumbersome. Using SwingWorker is alleviates the problem a little. It's guaranteed to behave properly while starting, running and updating GUI (each has a dedicated method which you can override and be sure it runs on proper thread).

这篇关于摆动:如何从AWT线程运行作业,但在窗口布局之后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 17:16