I have been struggled to solve this problem for few days, i was working on multichat application where in this class i want to send the text to the server and and response in the client side, if anyone can help me i really appreciate

from what i known the error shown at MyChatPage.java:43, which is

out.println(txtmsg.getText());

it is something related null value in either Print Writer or txtmsg.getText(), but no matter what i done still cannot solve.
Here is my other codes

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at MyChatPage$1.actionPerformed(MyChatPage.java:43)
    at javax.swing.JTextField.fireActionPerformed(JTextField.java:508)
    at javax.swing.JTextField.postActionEvent(JTextField.java:721)
    at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:836)
    at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1664)
    at javax.swing.JComponent.processKeyBinding(JComponent.java:2879)
    at javax.swing.JComponent.processKeyBindings(JComponent.java:2926)
    at javax.swing.JComponent.processKeyEvent(JComponent.java:2842)
    at java.awt.Component.processEvent(Component.java:6282)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1895)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:762)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1027)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:899)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:727)
    at java.awt.Component.dispatchEventImpl(Component.java:4731)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:688)
    at java.awt.EventQueue$3.run(EventQueue.java:686)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:702)
    at java.awt.EventQueue$4.run(EventQueue.java:700)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

client

public class MyChatPage extends javax.swing.JFrame {
BufferedReader in;
PrintWriter out;
private static String PassAddress;
private static String PassName2;
private static String PassEmail2;

public MyChatPage() {
        initComponents();

       txtmsg.addActionListener(new ActionListener() { 
            /**
             * Responds to pressing the enter key in the textfield by sending
             * the contents of the text field to the server.    Then clear
             * the text area in preparation for the next message.
             */
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, out);
                JOptionPane.showMessageDialog(null, txtmsg.getText());
                out.println(txtmsg.getText());

                out.flush();
                txtmsg.setText("");
            }
        });
    }
//------Pass value from IP------------------------------------------------------
    public void setAddress(String sA)
    {
        PassAddress = sA;
    }
    public String getAddress()
    {
        return PassAddress;
    }
    public void setName2(String sN2)
    {
        PassName2 = sN2;
        txtuserlist.append(PassName2 + "\n");
    }
    public String getName2()
    {
        return PassName2;
    }
    public void setEmail2(String sE2)
    {
        PassEmail2 = sE2;
    }
    public String getEmail2()
    {
        return PassEmail2;
    }
//------------------------------------------------------------------------------
private void run() throws IOException {

        // Make connection and initialize streams
        String serverAddress2 = getAddress();
        Socket socket = new Socket(serverAddress2, 1235);
        in = new BufferedReader(new InputStreamReader(
            socket.getInputStream()));
        out = new PrintWriter(socket.getOutputStream(), true);

        // Process all messages from server, according to the protocol.

        while (true) {
            String line = in.readLine();
            out.println(line + "\r\n");
            out.flush();
            if (line.startsWith("SUBMITNAME")) {
                out.println(getName2());
            } else if (line.startsWith("NAMEACCEPTED")) {
                txtmsg.setEditable(true);
            } else if (line.startsWith("MESSAGE")) {
                txtmsgarea.append(line.substring(8) + "\n");
            }
        }
    }

     public static void main(String args[]) throws Exception  {
        MyChatPage mcp = new MyChatPage();
        mcp.run();
    }

server side

public class MyChatServer {

    private static final int PORT = 1235;
    private static HashSet<String> names = new HashSet<String>();
    /**
     * The set of all the print writers for all the clients. This set is kept so
     * we can easily broadcast messages.
     */
    private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();

    /**
     * The application main method, which just listens on a port and spawns
     * handler threads.
     */
    public static void main(String[] args) throws Exception {

        System.out.println("MyChat server is running.");
        ServerSocket listener = new ServerSocket(PORT);

        try {
            while (true) {
                new Handler(listener.accept()).start();
            }
        } finally {
            listener.close();
        }

    }

    private static class Handler extends Thread {

        private Socket socket;
        private BufferedReader in;
        private PrintWriter out;
        private String name;

        /**
         * Constructs a handler thread, squirreling away the socket. All the
         * interesting work is done in the run method.
         */
        public Handler(Socket socket) {
            this.socket = socket;
        }

        /**
         * Services this thread's client by repeatedly requesting a screen name
         * until a unique one has been submitted, then acknowledges the name and
         * registers the output stream for the client in a global set, then
         * repeatedly gets inputs and broadcasts them.
         */
        public void run() {
            try {

                // Create character streams for the socket.
                in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                while (true) {
                    out.println("SUBMITNAME");
                    name = in.readLine();
                    if (name == null) {
                        return;
                    }
                    synchronized (names) {
                        if (!names.contains(name)) {
                            names.add(name);
                            break;
                        }
                    }
                }

                out.println("NAMEACCEPTED");
                writers.add(out);

                while (true) {
                    String input = in.readLine();
                    if (input == null) {
                        return;
                    }
                    for (PrintWriter writer : writers) {
                        writer.println("MESSAGE " + name + ": " + input);
                    }
                }

            } catch (IOException e) {
                System.out.println(e);
            } finally {
                if (name != null) {
                    names.remove(name);
                }
                if (out != null) {
                    writers.remove(out);
                }
                try {
                    socket.close();
                } catch (IOException e) {
                }
            }

        }
    }
}

That's not enough of the code to see why a variable should still be null, but for starters try printing out and txtmsg just before that line to see which is null.

i have using Joption to check and the

out

in the actionperformed was null

Edited 2 Years Ago by Vegito1991

Unless there's a duplicate declaration of out somewhere, that implies that the actionPerformed has been called before run gets to line 61.
Maybe it's hanging on the new Socket or maybe it's thrown an IOException (because I can't see any code to handle that Exception)

For more information, i wonder the duplicate declaration u mean which point to both IP checking page and Client class?
login page

public class MyChatLogin extends javax.swing.JFrame {
private Connection con;
private PreparedStatement st;
private ResultSet rs;
private String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
private String db = "jdbc:odbc:MyChatdata";
    /**
     * Creates new form MyChatLogin
     */
    public MyChatLogin() {
        initComponents();
        connect();  
    }

    MyChatLogin(String st) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
        public void connect() {
    try
    {
        Class.forName(driver);
        con = DriverManager.getConnection(db);
    }
    catch (Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPasswordField1 = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtuser = new javax.swing.JTextField();
        txtpass = new javax.swing.JPasswordField();
        btlogin = new javax.swing.JButton();
        btquit = new javax.swing.JButton();

        jPasswordField1.setText("jPasswordField1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Username");

        jLabel2.setText("Password");

        txtuser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtuserActionPerformed(evt);
            }
        });

        btlogin.setText("Login");
        btlogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btloginActionPerformed(evt);
            }
        });

        btquit.setText("Quit");
        btquit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btquitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(76, 76, 76)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btlogin)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btquit))
                    .addComponent(txtuser)
                    .addComponent(txtpass))
                .addContainerGap(79, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(4, 4, 4)
                .addComponent(txtuser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtpass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btlogin)
                    .addComponent(btquit))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void txtuserActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       

    private void btquitActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
        System.exit(0);
    }                                      

    private void btloginActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        String user_login="Select * from MyChatUser where Username = ? and Userpass = ?";
       try
       {
           st = con.prepareStatement(user_login);
           st.setString(1, txtuser.getText());
           st.setString(2, txtpass.getText());
           rs = st.executeQuery();
           if((txtuser.getText().trim().length() == 0) || (txtpass.getText().trim().length() == 0))
           {
               JOptionPane.showMessageDialog(null, "Insert Username and Password!");
           }
           else if(rs.next())
           {
               JOptionPane.showMessageDialog(null, "Login Success!");
               String userEmail = rs.getString("Email");
               String userName = rs.getString("ChatName");

                   //MyChatIP client = new MyChatIP();
                   //client.setEmail(userEmail);
                  // client.setName(userName);
                 //  client.setVisible(true);
                 //  client.setLocationRelativeTo(null);
                   this.dispose();
                   MyChatPage cp = new MyChatPage();
                     cp.setVisible(true);
                     cp.setLocationRelativeTo(null);

           }
           else
               JOptionPane.showMessageDialog(null, "Invalid Username or Password!");
       }
       catch (Exception e)
       {
           JOptionPane.showMessageDialog(null, e);
       }
    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MyChatLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MyChatLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MyChatLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MyChatLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MyChatLogin().setVisible(true);
            }
        });
    }

Ip checking

public class MyChatIP extends javax.swing.JFrame {
BufferedReader in;
PrintWriter out;
private static String PassEmail;
private static String PassName;
    /**
     * Creates new form MyChatIP
     */
    public MyChatIP() {
        initComponents();
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
//-------Pass value from login--------------------------------------------------
    public void setEmail(String sE)
    {
        PassEmail = sE;
    }
    public String getEmail()
    {
        return PassEmail;
    }
    public void setName(String sN)
    {
        PassName = sN;
    }
    public String getName()
    {
        return PassName;
    }
//------------------------------------------------------------------------------
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtip = new javax.swing.JTextField();
        btok = new javax.swing.JButton();
        btbackl = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MyChat Server Connection");

        jLabel1.setText("Please Insert IP address");

        btok.setText("OK");
        btok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btokActionPerformed(evt);
            }
        });

        btbackl.setText("Back");
        btbackl.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btbacklActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(83, 83, 83)
                .addComponent(btok)
                .addGap(18, 18, 18)
                .addComponent(btbackl)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(txtip))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(88, 88, 88)
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btbackl)
                    .addComponent(btok))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void btokActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // TODO add your handling code here:
        String serveraddress = txtip.getText();
    try {
            Socket socket = new Socket(serveraddress, 1235);
        in = new BufferedReader(new InputStreamReader(
            socket.getInputStream()));
        out = new PrintWriter(socket.getOutputStream(), true);

            MyChatPage cp = new MyChatPage();
            cp.setAddress(serveraddress);
            cp.setName2(PassName);
            cp.setEmail2(PassEmail);
            cp.setVisible(true);
            cp.setLocationRelativeTo(null);
            JOptionPane.showMessageDialog(null, "MyChat Server Connection Success!");
            this.dispose();

    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Connect Fail!");
    }
    }                                    

    private void btbacklActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
       MyChatLogin mcl = new MyChatLogin();
       mcl.setVisible(true);
       this.dispose();
    } 

Edited 2 Years Ago by Vegito1991

i have found the problem, seems like because i using new object to open the jframe and this new object has cause my out become null, any idea how to open new jframe without lose its value?

I'm sorry, but you have posted hundreds of lines of undocumented code with no apparent overall structure, multiple main methods, multiple declarations of variables with the same name, code that refers to variables that are not declared in that class, and I have absolutely no idea what the flow of control is to ensure everything is initialised properly.

All I can suggest is that you trace the value of out up to the point where you try to use it and it is null. Presumably you have a plan for how it gets initialised, and you need to find out where the execution deviates from that plan.

This question has already been answered. Start a new discussion instead.