代码在最下面,我把问题写在代码里,其他注释删除了,为了方便各位看到我的问题,非常感谢
先上群里问的结果:
没有解决,下一个(图片里的其他言论我打马赛了):
我在代码里添加了:
outgoing 是单行消息框,如果writer没有被实例化它就是空的,按下send按钮消息框里会显示true,我的测试结果:
正题来了~ :
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleChatClient {
JTextField outgoing;//单行消息框
PrintWriter writer;
Socket socket;
public void go() {
JFrame frame = new JFrame("Ludicrously Simple Chat Client");
JPanel mainPanel = new JPanel();
outgoing = new JTextField(20);
JButton sendButton = new JButton("Send");
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(outgoing);
mainPanel.add(sendButton);
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
setUpNetworking();
frame.setSize(400, 500);
frame.setVisible(true);
}
private void setUpNetworking() {
try {
socket = new Socket("127.0.0.1",5000);
writer = new PrintWriter(socket.getOutputStream());//方法里面实例化,局域对象,当方法结束它就不存在了
System.out.println("networking established");
}catch(IOException e) {
e.printStackTrace();
}
}
public class SendButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev) {
try {
/**
* 程序正常运行
* 这里明明没有实例化
* 却可以调用方法
* 而且正常运行
* 它怎么可以?好迷惑-.-
*/
writer.println(outgoing.getText());
writer.flush();
}catch(Exception e) {
e.printStackTrace();
}
boolean a = writer == null;//这句不需要 刚刚为了测试这个writer是否为空添加的,当按下send按钮时单行消息框里面显示判断结果
outgoing.setText(""+a);//单行消息框显示内容
outgoing.requestFocus();
}
}
public static void main(String[]args) {
new SimpleChatClient().go();
}
}