执行中的线程睡眠 [英] Thread sleep in actionPerformed

查看:110
本文介绍了执行中的线程睡眠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to make a tiny program that has 3 buttons, all of them of white color. Pressing the first button (that has the text "Go!") will cause the second button to become orange for 3 seconds and then, after that time, it will become white again AND the third button will become permanently green.

但是,在我的以下代码中,实现此目标有一个问题:按下按钮 Go!时,它会使我的程序冻结3秒钟,然后第三个按钮变为绿色。

However, in my following code, I have a problem achieving this: When hitting the button "Go!", it causes my program to somewhat freeze for 3 seconds and then the third button becomes green. Can you please help me?

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");
}
}


推荐答案

摇摆是单线程的。在 EDT 中调用 Thread.sleep 可以防止UI更新。使用 Swing Timer

Swing is single threaded. Calling Thread.sleep in the EDT prevents UI updates. Use a Swing Timer instead.

这篇关于执行中的线程睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆