【问题标题】:Pausing execution of code in the actionPerformed() method of ActionListener在 ActionListener 的 actionPerformed() 方法中暂停执行代码
【发布时间】:2019-09-26 16:49:58
【问题描述】:

我有这个actionPerformed 方法可以抽两张牌。在抽那两张牌之间,我想暂停程序一段时间,这样我就可以一张一张地看到抽牌。我尝试了Thread.sleep() 方法,但它只是在执行actionPerformed 方法后暂停程序。

【问题讨论】:

    标签: java swing event-handling


    【解决方案1】:

    因为 Swing 事件线程中长时间运行的操作(如暂停)会冻结 UI,所以不推荐使用此策略。相反,也许可以考虑使用Timer 来触发与第二张卡片的绘制相对应的第二个事件,如下例所示。

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

    【讨论】:

      猜你喜欢
      • 2013-03-27
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 2015-09-05
      • 2017-06-20
      • 2021-04-05
      相关资源
      最近更新 更多