我目前正在为我的学校作业开发聊天机器人。我完成了整个聊天部分,使用扫描仪进行用户输入,并使用System.out.println()显示对话。 现在我想为chatbot实现一个GUI。我得到了一个非常简单的GUI,分别是JTextField和JTextArea分别是输入框和显示框。在Java中重定向输入和输出
但现在我完全无法知道如何将它们连接在一起。 这就像扫描仪,而不是System.in,将读取来自JTextField的输入,而不是在控制台中显示输出,将它们显示在JTextArea中。
任何人都可以帮助我吗?像我应该学会如何将chatbot和GUI链接在一起?
如果你想看看我的GUI代码,它是如下:
public class GUI_V2 extends JFrame {
private JTextField txtEnter = new JTextField();
//Chat area;
private JTextArea txtChat = new JTextArea();
//Scroll
private final JScrollPane scroll = new JScrollPane(txtChat);
public GUI_V2(){
//Frame Attributes
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(2000,2000);
this.setVisible(true);
this.setResizable(false);
this.setLayout(null);
this.setTitle("Menu ChatBot");
//textEnter Attributes
txtEnter.setLocation(20,1825);
txtEnter.setSize(1950,100);
txtEnter.setFont(new Font("Arial",Font.PLAIN,45));
//txtChat Attributes
txtChat.setLocation(22,5);
txtChat.setSize(1950,1800);
txtChat.setFont(new Font("Arial",Font.BOLD,45));
txtChat.setBackground(java.awt.Color.getHSBColor(0.4957f,0.0902f,1.0f));
txtChat.setLineWrap(true);
txtChat.setWrapStyleWord(true);
txtChat.setEditable(false);
//scroll Attributes
scroll.setLocation(22,5);
scroll.setSize(1950,1800);
//Add Items To Frame
this.add(txtEnter);
this.add(scroll);
//txtEnter Action Event:
txtEnter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
//add userInput into the txtChat
String uText = txtEnter.getText();
txtChat.append("You" + ": " + uText + "\n");
//auto scroll down
txtChat.setCaretPosition(txtChat.getDocument().getLength());
//set the txtEnter field to be empty
txtEnter.setText("");
}
});
}
好了,你的投入似乎恰到好处。可悲的是你不显示你的输出。 – XtremeBaumer
所以你需要添加JTextField的值到JTextArea当按钮点击或焦点改变或什么? – Blasanka
没有。GUI很好。我想将chatbot类的输出指向GUI的JTextArea。并使用JTextField的输入作为我的聊天机器人的输入 –