Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 暂停ActionListener的actionPerformed()方法中的代码执行_Java_Swing_Event Handling - Fatal编程技术网

Java 暂停ActionListener的actionPerformed()方法中的代码执行

Java 暂停ActionListener的actionPerformed()方法中的代码执行,java,swing,event-handling,Java,Swing,Event Handling,我执行了这个操作方法,可以画两张牌。在这两张卡片的绘制之间,我想将程序暂停一段时间,以便我能够逐个查看卡片的绘制。我尝试了Thread.sleep()方法,但它只是在执行actionPerformed方法后暂停程序 由于Swing事件线程中的长时间运行操作(如暂停)将冻结UI,因此不建议使用此策略。取而代之的是,可以考虑使用A来触发与第二张卡片相对应的第二个事件,如下面的例子。 public static void main(String[] args) { SwingUtilities

我执行了这个
操作
方法,可以画两张牌。在这两张卡片的绘制之间,我想将程序暂停一段时间,以便我能够逐个查看卡片的绘制。我尝试了
Thread.sleep()
方法,但它只是在执行
actionPerformed
方法后暂停程序

由于Swing事件线程中的长时间运行操作(如暂停)将冻结UI,因此不建议使用此策略。取而代之的是,可以考虑使用A来触发与第二张卡片相对应的第二个事件,如下面的例子。
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);
    });
}

由于Swing事件线程中的长时间运行操作(如暂停)将冻结UI,因此不建议使用此策略。取而代之的是,可以考虑使用A来触发与第二张卡片相对应的第二个事件,如下面的例子。
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);
    });
}