在ActionListener的actionPerformed()方法中暂停执行代码 [英] Pausing execution of code in the actionPerformed() method of ActionListener

查看:276
本文介绍了在ActionListener的actionPerformed()方法中暂停执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个actionPerformed方法可以抓两张牌.在这两张牌的抽签之间,我想暂停程序一定时间,以便能够一张一张地看到卡的抽签.我尝试了Thread.sleep()方法,但是在执行actionPerformed方法后它只是暂停了程序.

I have this actionPerformed method that draws two cards. In between of drawing of those two cards I want to pause the the program for a certain amount of time so that I will be able see drawing of cards one by one. I tried Thread.sleep() method but it just pauses the program after the execution of actionPerformed method.

推荐答案

由于Swing事件线程中的长时间运行操作(如暂停)将冻结UI,因此不建议使用此策略.相反,可以考虑使用 Timer 来触发与第二张卡片的图形相对应的第二个事件,如下例所示.

Because a long-running operation (like pausing) in the Swing event thread will freeze the UI, this is not a recommended strategy. Instead, maybe consider using a Timer to fire a second event that corresponds to the drawing of the second card, as in the example below.

public static void main(String[] args) {
    SwingUtilities.invokeLater(()-> {
        JFrame frame = new JFrame();
        JButton button = new JButton("Ok");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("First card");
                Timer timer = new Timer(2000, new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("Second card");
                    }
                });
                timer.setRepeats(false);
                timer.start();
            }
        });
        frame.add(button);
        frame.pack();
        frame.setVisible(true);
    });
}

这篇关于在ActionListener的actionPerformed()方法中暂停执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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