如何在不冻结线程的情况下延迟回答?

How to delay an answer while not freezing the thread?

简单的问题。 Thread.sleep(x) 冻结整个代码,所以即使按钮保持原样(按下未按下的任何东西)

我基本上想点击一个按钮,“等待”计算机在 x 时间内完成它,然后输出一些东西。

public class bsp extends JFrame {
DrawPanel drawPanel = new DrawPanel();

public bsp() {
    setSize(600,600);
    JButton Hit = new JButton("Hit him");
    Hit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            System.out.println("I hit you back!");
            
        }
    });
    Hit.setSize(80, 30);
    Hit.setLocation(200, 400);
    add(Hit);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    add(drawPanel);
    setVisible(true);

}

private static class DrawPanel extends JPanel {

    protected void paintComponent(Graphics g) {
        
    }
}

public static void main(String[] args) {
    new bsp();

}

}

如您所见,按钮“保持”按下状态,整个程序被冻结。 但我基本上想模拟“A.I”。先思考再回答,不要冻结一切。

考虑使用 Timer 来防止主线程冻结:

import javax.swing.*;
import java.awt.event.*;

        ActionListener task = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
             
            }
        };
        Timer countdown = new Timer(1000 ,task);
        countdown.setRepeats(false);
        countdown.start();

其中 1000 是以毫秒为单位的延迟时间,actionPerformed 函数内部是您的代码在延迟时间设置后执行的位置。