AI: Enter 1 to add question to chatbot.
AI: Enter 2 to start chatting with bot.
AI: Enter 3 to end chatbot.
[You] 1
[You] hi
AI: Hello there!
[You] hi上图是在图形用户界面jtextarea JFrame中,如何删除"AI: Hello there!“之后的最后一个"You hi”?只有一个"hi“是我写的jtextfield,但它却回复了2个"hi”。或者,有没有比这更简单的方法让我写一段代码,可以选择多个其他类的“函数”?以下是我拥有的代码。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class GUItest2 extends JFrame {
private JTextField userinput = new JTextField();
private JTextArea scriptarea = new JTextArea();
private String stringinput;
public GUItest2() {
// Frame Attributes:
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 600);
this.setVisible(true);
this.setResizable(false);
this.setLayout(null);
this.setTitle("Java AI");
setLocationRelativeTo(null);
userinput.setLocation(2, 540);
userinput.setSize(590, 30);
scriptarea.setLocation(15, 5);
scriptarea.setSize(560, 510);
scriptarea.setEditable(false);
this.add(userinput);
this.add(scriptarea);
selectionfunction();
// chatfunction();
}
public void textarea() {
// userinput.addActionListener(new ActionListener(){
// public void actionPerformed(ActionEvent arg0){
stringinput = userinput.getText();
scriptarea.append("[You] " + stringinput + "\n");
// }
// });
}
public void selectionfunction() {
botreply("Enter 1 to add question to chatbot.");
botreply("Enter 2 to start chatting with bot.");
botreply("Enter 3 to end chatbot.");
userinput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textarea();
if (stringinput.contains("1")) {
chatfunction();
}
userinput.setText("");
}
});
}
public void chatfunction() {
userinput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textarea();
if (stringinput.contains("hi")) {
botreply("Hello there!");
} else if (stringinput.contains("how are you")) {
int decider = (int) (Math.random() * 2 + 1);
if (decider == 1) {
botreply("I'm doing well, thanks");
} else if (decider == 2) {
botreply("Not too bad");
}
} else {
int decider = (int) (Math.random() * 3 + 1);
if (decider == 1) {
botreply("I didn't get that");
} else if (decider == 2) {
botreply("Please rephrase that");
} else if (decider == 3) {
botreply("???");
}
}
}
});
}
public void botreply(String s) {
scriptarea.append("AI: " + s + "\n");
}
public static void main(String[] args) {
new GUItest2();
}
}发布于 2017-08-02 23:10:19
你的问题有几个原因;
首先,您声明了两次userinput.addActionListener,这导致每当文本框提交一个值时,textarea()方法都会被调用两次。
其次,在chatfunction()方法中,不能在ActionListener末尾重置userinput。这就是为什么它会打印你的原始输入两次。
最后,每当调用textarea()方法时,您都会检索userinput的值并将其附加到聊天中,而不管它是什么。考虑在第一次检查是否有要追加的输入时添加一条if语句。例如if(!stringinput.equals("")) scriptarea.append("[You] " + stringinput + "\n");
正如Pshemo上面所说的,在你的代码流中还有其他问题你应该寻求解决,即从另一个内部调用一个新的ActionListener。
https://stackoverflow.com/questions/45463902
复制相似问题