[英]Java: Easier way to implement delay into a chat bot response system?
我试图在用户输入和 bot output 之间获得几秒钟的延迟; 这就是我目前所拥有的。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ChatBot extends JFrame {
private JTextArea Chatarea = new JTextArea();
private JTextField chatbox = new JTextField();
public ChatBot () {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
frame.setLayout(null);
frame.setSize(600, 600);
frame.setTitle("ChatBot");
frame.add(Chatarea);
frame.add(chatbox);
//Text Area
Chatarea.setSize(500 , 450);
Chatarea.setLocation(10, 5);
//Text Field
chatbox.setSize(510 , 30);
chatbox.setLocation(10 , 500);
chatbox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String gtext = chatbox.getText();
Chatarea.append("YOU: " + gtext + "\n");
chatbox.setText("");
if(gtext.contains("Hi")) {
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
bot("Hello.");
}
}, 2000);
}
else {
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
bot("What was that?");
}
}, 2000);
}
}
}
);}
private void bot(String string) {
Chatarea.append("Bot: " + string + "\n");
}
public static void main(String[] args) {
new ChatBot();
}
}
它工作正常,但我宁愿在一个位置有延迟命令并在需要时调用它,或者只是在用户输入后立即放置延迟。 我尝试将计时器放入它自己的 function 中,但后来我不确定如何将聊天机器人的响应放入public void run() {}
中,或者我是否以正确的方式进行此操作。
所以你需要一个 function void respondDelayed(String message, int delayMillis)
?
关于什么:
void respondDelayed(String message, int delayMillis) {
new Timer().schedule(
new TimerTask() {
@Override
public void run() { bot(message); }
}, delayInMillis);
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.