问题描述
- 自己写的Client端提示空指针
-
public class ChatClient {
static Socket s;
static DataOutputStream dos;
static String str;
static TextField txt;
static TextArea content;public static void main(String[] args){ new MyFrame().LaunchFrame(); } static class MyFrame extends Frame{ public void LaunchFrame(){ setLocation(300,300); setSize(300,400); setBackground(Color.PINK); setTitle("WeChat"); add(txt,BorderLayout.SOUTH); add(content,BorderLayout.NORTH); pack(); this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ disconnected(); System.exit(0); } }); setVisible(true); } } public void connect() throws UnknownHostException, IOException{ s = new Socket("127.0.0.1",8888); dos = new DataOutputStream(s.getOutputStream()); System.out.println("connected"); } private class TFListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub str = txt.getText().trim(); content.setText(str); txt.setText(""); } } public static void disconnected(){ try { dos.writeUTF(str); dos.flush(); s.close(); dos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
解决方案
add(txt,BorderLayout.SOUTH);
add(content,BorderLayout.NORTH);
这两句的txt和content没有new出来。
时间: 2024-09-22 15:10:53