线程睡眠在actionPerformed方法中 [英] Thread sleep inside of actionPerformed method
问题描述
首先,我想说我知道这种方法是错误的所以我问这个问题是因为纯粹的好奇心。假设我有这样的swing应用程序:
First of all I want to say I'm aware this aproach is wrong so I'm asking this question because of pure curiousity. Lets say I have a swing application like this:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ThreadSleeping {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("Load");
JLabel label = new JLabel();
public ThreadSleeping() {
panel.add(button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
label.setIcon(new ImageIcon(
"C:/Users/Public/Pictures/Sample Pictures/Tulips.jpg"));
System.out.println("Tulips painted");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
label.setIcon(new ImageIcon(
"C:/Users/Public/Pictures/Sample Pictures/Koala.jpg"));
System.out.println("Koala painted");
}
});
frame.add(panel, BorderLayout.NORTH);
frame.add(label, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(1024, 768);
// frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ThreadSleeping();
}
});
}
}
基本上当我点击加载
按钮我希望显示 Tulips.jpg
图像,然后GUI冻结2秒钟,之后我希望考拉.jpg
图像显示。但是会发生什么:我点击按钮,GUI冻结2秒钟,显示 Koala.jpg
。之前没有 Tulips.jpg
。但令我困惑的是当我把那些 System.out.println(郁金香画);
和 System.out.println(考拉时涂);
。因此,当我点击按钮时,它会打印郁金香画,并在2秒后考拉画。谁能告诉我这里发生了什么?问候。
Basically when I click a Load
button I expect that Tulips.jpg
image displays then GUI freezes for a 2 seconds and after that I expect that Koala.jpg
image displays. But what happens is that: I click on button, GUI freezes for a 2 seconds and Koala.jpg
displays. No Tulips.jpg
before that. But thing that confuses me is when I put those System.out.println("Tulips painted");
and System.out.println("Koala painted");
. So when I click on button it prints "Tulips painted" and after 2 seconds "Koala painted". Can someone tell me whats going on here? Regards.
推荐答案
works in this case, because you programatically freeze ouf Swing GUI, but there is/aren't another update(s), ot another JComponent(s)
如果有一些其他更新到Swing GUI,Thread.sleep(int)冻结事件调度线程,
doens't works in the case that there are a few another updated to the Swing GUI, Thread.sleep(int) freeze Event Dispatch Thread,
默认情况下, JComponents XxxModels
的所有更新都不会出现在 JComponents视图中
by default all updates to the JComponents XxxModels
never will be visible on the JComponents view
这篇关于线程睡眠在actionPerformed方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!