【发布时间】:2014-11-20 02:20:33
【问题描述】:
我已经实现了一个聊天客户端。到目前为止,它只能在 cmd 中完全运行,因为我不知道应该如何在聊天客户端 GUI 中实现发送按钮。
这是我的聊天客户端类:
class ChatClientClass {
private String host;
private int port;
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private BufferedReader stdIn;
ChatWindow chatWindow = new ChatWindow();
public ChatClientClass(String host, int port) {
try {
this.socket = new Socket(host, port);
this.out =
new PrintWriter(socket.getOutputStream(), true);
this.in =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
this.stdIn =
new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
chatWindow.addText("You: " + userInput);
String serverMessage = in.readLine();
chatWindow.addText(serverMessage);
}
} catch (UnknownHostException e) {
System.err.println("Couldn't not find host " + host);
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " + host);
e.printStackTrace();
System.exit(1);
}
}
}
到目前为止,我只能在命令提示符下写东西。但是我所写的以及服务器回答的内容将出现在我的 GUI 中。 addText(String text)-方法将输入和输出添加到我的 GUI。
但我不知道如何实现我的发送按钮。一种简单的方法是,当我调用 ActionListener 类的构造函数时,我可以发送对 PrintWriter 的引用和对 GUI 的引用,然后执行以下操作:public void actionPerformed(ActionEvent e) 方法中的thePrintWriter.println( [get the value of the text area that belongs to the send button] )。但是由于我不能/不应该从我的聊天客户端类调用我的 ActionListener 的构造函数,因此发送这些引用。这不可能吧?
我还考虑过将 PrintWriter 变量设为静态,并将包含我要发送的消息的 JTextArea 设为静态,然后创建静态方法来访问这两个变量。但是当我这样做时,感觉就像我在做一些非常错误的事情。我也无法让它工作。
那么聊天客户端中的发送按钮应该如何实现呢?
提前致谢!
【问题讨论】:
标签: java user-interface client chat send