Search code examples
javaclasssocketsglobalprintwriter

trouble using printwriter from another class


My main problem is that I get a nullpointerexception when I use ChatPanel.pw.println(ChatPanel.name + " has disconnected from the chat.") while printwriter is in the ChatPanel class and I'm trying to use the printwriter to send the message through the socket. If someone help me understand and maybe give me a solution to the problem. I did remove a lot of code but, it should compile.

import java.io.*;
import java.awt.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.JComponent;
public class ChatFrame1 extends JFrame{


   public ChatFrame1(){
      setLayout(new GridBagLayout());
      setSize(1000,600);
        setTitle("Chat");
      setResizable(true);  
      addWindowListener(new WindowAdapter(){

        public void windowClosing(WindowEvent we){

            //The problem is here.
            ChatPanel.pw.println(ChatPanel.name + " has disconnected from the chat.");
            System.out.println(ChatPanel.name);
            System.exit(0);
        }
      });
      ChatPanel sp = new ChatPanel();
      setVisible(true);
   }
   public static void main(String[] args){
        new ChatFrame1();

    }
}
class ChatPanel extends JPanel implements ActionListener, Runnable{
    Thread t;
    JTextField tf;
    JTextArea ta;
    JButton b;
    Socket s;
    BufferedReader br;
    public static PrintWriter pw;
    String temp;
    boolean connected;
    public static String name;

    public ChatPanel(){

        GridBagConstraints gbc = new GridBagConstraints();
        name = (String)JOptionPane.showInputDialog(null,"Enter A Username "+
                "(Please Only Use Letters And Numbers) :", 
                "Username Login",
                JOptionPane.PLAIN_MESSAGE, null, null, "User-Name");
        setLayout(new GridBagLayout());
        tf = new JTextField();
        tf.addActionListener(this);
        ta = new JTextArea();
        b = new JButton("Press To Connect");
        b.addActionListener(this);

    }
    public void actionPerformed(ActionEvent ae){
        if((tf != null) && (!connected)){

        b.setLabel("Press to Connect");
        }
        if((ae.getSource() == b) && (!connected)){
            try{
                s = new Socket("127.0.0.1", 2020);
                pw = new PrintWriter(s.getOutputStream(), true);
                tf.setText("");

            }catch(UnknownHostException uhe){
                System.out.println(uhe.getMessage());


            }catch(IOException ioe){

                System.out.println(ioe.getMessage());

            }   
            connected = true;
            t = new Thread(this);
            b.setLabel("Disconnect");
            t.start();

        }else if((ae.getSource() == b) && (connected)){  
            connected = false;
            try{
                pw.println(name +" has disconnected from the chat.");
                ta.setText("");
                s.close(); //no buffering so, OK
            }catch(IOException ioe){
                System.out.println(ioe.getMessage());
            }
            b.setLabel("Press to Reconnect");
        }else{
        temp = tf.getText();
            tf.setText("");
        }
    }
    public void run(){

        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            while(((temp = br.readLine()) != null) && connected){
            ta.append(temp + "\n");
            }
        }catch(IOException ioe){
            System.out.println(ioe.getMessage());
        }
    }
}

Solution

  • I think this is giving you the NullPointerException

    ChatPanel.pw.println(ChatPanel.name + " has disconnected from the chat.");
    

    because ChatPanel.pw has never been initialized in your code, and therefore is null

    You should ensure that ChatPanel.pw has been initialized somewhere (maybe within the constructor) inside your ChatPanel class before calling the ChatPanel.pw.println()