Pausing execution of code in the actionPerformed() method of ActionListener

时光怂恿深爱的人放手 提交于 2019-12-13 20:43:21

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/58121425/pausing-execution-of-code-in-the-actionperformed-method-of-actionlistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!