0

我有下面显示的内部类。这是针对客户端/服务器的,我在 PrintWriter 的“println”处有空指针异常。我已经尝试了我所知道的一切来解决它,但是没有成功。任何人都可以给我一个小费或我必须做什么的想法。多谢你们!

这是完整的类代码:

public class ChatClient extends JFrame{
    private JTextField textToSend;
    private Socket socket;
    private PrintWriter writer
    private String name;
    private JTextArea receivedText;
    private Scanner reader;

    public ChatCliente(String name){
        super("Chat: "+ name);
        this.name = name;
        Font font = new Font("Serif", Font.PLAIN, 20);
        textToSend = new JTextField();
        textToSend.setFont(font);
        JButton btn = new JButton("Send");
        btn.setFont(font);
        btn.addActionListener(new Listener());
        Container content = new JPanel();
        content.setLayout(new BorderLayout());
        content.add(BorderLayout.CENTER, textToSend);
        content.add(BorderLayout.EAST, btn);

        receivedText = new JTextArea();
        receivedText.setFont(font);
        JScrollPane scroll = new JScrollPane(receivedText);

        getContentPane().add(BorderLayout.CENTER, scroll);
        getContentPane().add(BorderLayout.SOUTH, content);
        configureNetwork();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500,500);
        setVisible(true);
    }

    private void configureNetwork(){
        try{
            socket = new Socket("127.0.0.1",5000);
            writer = new PrintWriter(socket.getOutputStream());
            reader = new Scanner(socket.getInputStream());
            new Thread(new ServerThread()).start();
        }catch (Exception e){}
    }

    private class Listener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            try{
                String s  = name;
                String t = textToSend.getText();
                System.out.println(name+" : "+ textToSend.getText());
                writer.println(s+" : "+t);
                writer.flush();
                textToSend.setText("");
                textToSend.requestFocus();
            }catch(Exception ex){
                ex.printStackTrace();
            }
        }
    }

    private class ServerThread implements Runnable{

        @Override
        public void run() {
           String text;
           try{
               while((text = reader.nextLine()) != null){
                   receivedText.append(text+"\n");
               }
           }catch(Exception e){}
        }
    }
}
4

2 回答 2

0

未声明“名称”。

也许你的意思是:

String s  = "name";
于 2013-09-26T21:14:33.737 回答
0

只是发生在我身上的一些愚蠢的事情:不要在文件名中插入“/”,否则它当然会寻找一个可能不存在的额外文件夹。

int number = 1, total = 126;
String path = "some/path/found " + number + "/" + total;
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(path, true)));
于 2015-07-20T03:56:30.037 回答