我目前正在爲我的學校作業開發聊天機器人。我完成了整個聊天部分,使用掃描儀進行用戶輸入,並使用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的輸入作爲我的聊天機器人的輸入 –