【问题标题】:Thread sleep in actionPerformedThread sleep in actionPerformed
【发布时间】:2013-05-11 14:33:37
【问题描述】:

我正在尝试制作一个有 3 个按钮的小程序,所有按钮都是白色的。按下第一个按钮(带有文本“Go!”)将导致第二个按钮变为橙色 3 秒钟,然后在此之后再次变为白色,第三个按钮将变为永久绿色。

但是,在我的以下代码中,我遇到了一个问题:当点击“Go!”按钮时,它会导致我的程序在某种程度上冻结 3 秒,然后第三个按钮变为绿色。你能帮帮我吗?

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

public class Example extends JFrame
{
public Example(String title)
{
    super(title);
    GridLayout gl = new GridLayout(3,1);
    setLayout(gl);

    final JButton b1 = new JButton("Go!");
    final JButton b2 = new JButton();
    final JButton b3 = new JButton();

    b1.setBackground(Color.WHITE);
    b2.setBackground(Color.WHITE);
    b3.setBackground(Color.WHITE);

    b1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            b2.setBackground(Color.ORANGE);
            try
            {
                Thread.sleep(3000);
            } catch (InterruptedException ie) {}
            b2.setBackground(Color.WHITE);
            b3.setBackground(Color.GREEN);
        }
    });                

    add(b1);
    add(b2);
    add(b3);

    setSize(50,200);
    setVisible(true);
}

public static void main(String[] args)
{
    Example ex = new Example("My Example");
}
}

【问题讨论】:

  • Thread.sleep 阻止美国东部时间!
  • Thread.sleep(...) in actionPerformed:只要说 NO。有关解决方案,请参阅 D 先生的答案。
  • 提示:1) 不要设置顶级容器的大小。而是布局内容并致电pack()。 2) 不要扩展框架或其他顶级容器。而是创建和使用一个实例。

标签: java swing actionlistener event-dispatch-thread thread-sleep


【解决方案1】:

Swing 是单线程的。在 EDT 中调用 Thread.sleep 会阻止 UI 更新。请改用Swing Timer

【讨论】:

  • Swing Timer 无疑是解决原始问题的方法。 1+
  • 感谢您的回答! SwingTimer 或 SwingWorker 会工作吗?由于我是这些新手,您能否为我的示例提供一些代码供我学习? :) 谢谢
  • @darkchampionz 按照教程进行操作,很简单。自己尝试一下,如果没有成功,请在此处发布,我们会为您提供帮助!
  • 好的!能给我个链接吗!? :D
  • 我建议您先阅读documentation,然后再查看this tutorialthis question
【解决方案2】:

您在主线程上调用Thread.sleep(3000)。因此,为什么您的程序会冻结三秒钟。正如@MarounMaroun 建议的那样,您应该使用SwingWorkerHere 是文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 2022-12-02
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    相关资源
    最近更新 更多