Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello there.

For two days i'm trying to figure out what am i doing wrong in the code bellow:
HTML
(receiving NullPointerException on actionPerformed method of sendButton, on line output.println(messageToServer);

Java
public class ChatApplication implements ActionListener{

	//here i've declared my variables JTextAreas, clientSocket, buttons, JFrame, String userName
	
	public ChatApplication(){}
	
	public ChatApplication(String userName,String serverName) throws UnknownHostException, IOException{
		//super(userName);
//		try{
		this.userName=userName;
		clientSocket=new Socket(serverName,11111);
		input=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		output=new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()),true);
		output.println(userName);
		new ServerMessageThread().start();
		
//		}catch(IOException e){
//			System.err.println(e.getMessage());
//		}
	}
	
	//creating my interface etc.
	sendButton.addActionListener(this);		
		connectButton.addActionListener(new ActionListener(){			
			public void actionPerformed(ActionEvent e){
				
				String userName=JOptionPane.showInputDialog(window,"Name: "," ",JOptionPane.PLAIN_MESSAGE);
				try{
					String serverName="localhost";
					new ChatApplication(userName, serverName);
					window.setTitle(userName);
										
				}catch(IOException ex){
					JOptionPane.showMessageDialog(window,"Clientul nu se poate conecta."+ex.getMessage().toString());
				}				
			}			
		});
		
		startServerButton.addActionListener(new ActionListener(){
			
			public void actionPerformed(ActionEvent e){
				Thread thread=new Thread(){
					public void run(){
						
						ChatServer server=new ChatServer();
						try {
							server.process();
						} catch (Exception e) {
							System.err.println(e.getMessage());
							e.printStackTrace();
						}
					}
				};
				
				thread.start();		
			}			
		});		
	}
	
	public static void main(String[] args) {
			
			ChatApplication program=new ChatApplication();
			program.createInterface();
	}
	

	public void actionPerformed(ActionEvent e) {
		
		if(e.getSource()==sendButton){
			sendFlag=true;
			
			try{
			String messageToServer=new String("");
			messageToServer=messageField.getText();
			//PipedOutputStream pipedOut=new PipedOutputStream();
				
			output.println(messageToServer);//<- this is where i get NullPointerException
			
			}catch(NullPointerException ex){
				System.err.println(ex.getMessage());
				ex.printStackTrace();
			}
		}
	}
	
	
	
	/*
	 * clasa se ocupa cu crearea unui thread pentru a putea citi de la server
	 */
	
	class ServerMessageThread extends Thread{
		
		
		public void run(){
			
			String serverResponse=new String();
			
				try {
					while(true){
					serverResponse=input.readLine();
					System.out.println(serverResponse);
					output.println(serverResponse); //and here sending a message to the server works
					ChatApplication.messagesTextArea.append(serverResponse+"\n");
					
					}
				} catch (IOException e) {
					ChatApplication.messagesTextArea.setForeground(Color.RED);
					ChatApplication.messagesTextArea.setText("Eroare citire de la server: "+e.getMessage());
				}
		}
	}
	
	/*
	 * clasa care se ocupa cu crearea firelor de executie a clientilor
	 */

}


When i click the sendButton i get NullPointerException. And I'm kinda stuck there. The outputStream works in the ServerMessageThread, but not when clicking my button. I know that it can be fixed, but at the moment i can't figure it out.

The ChatServer works, because i've tested it without using a client interface, tested it in the console. For every client i'm creating a thread.

I just need an idea.Thank you. Best regards.

P.S: i know that it isn't a good practice to put much code in the question, but i wanted to show you how i implemented the client app.
Posted
Updated 29-May-13 7:48am
v4
Comments
Richard MacCutchan 29-May-13 13:14pm    
You need to explain which line of code this occurs on, and what are the values of the various objects and variables at the time of the error.
nameJulian 29-May-13 13:22pm    
The exception occurs in the actionPerformed method of sendButton, on the line: output.println(messageToServer);

1 solution

Java
public static void main(String[] args) {
			
	ChatApplication program=new ChatApplication(); //calling noarg constructor
	program.createInterface();
}


I see, You do all stream initialisation in the parameterized ctor (constructor) but you are calling the default ctor. Every thing is kept null so, NullPointerException.

Now here
Java
sendButton.addActionListener(this);		
		connectButton.addActionListener(new ActionListener(){			
			public void actionPerformed(ActionEvent e){
				
				String userName=JOptionPane.showInputDialog(window,"Name: "," ",JOptionPane.PLAIN_MESSAGE);
				try{
					String serverName="localhost";
					new ChatApplication(userName, serverName); //call to appropriate constructor
					window.setTitle(userName);
										
				}catch(IOException ex){
					JOptionPane.showMessageDialog(window,"Clientul nu se poate conecta."+ex.getMessage().toString());
				}				
			}			
		});


Here you call the required ctor and start a thread, the ctor, initializes the streams and hence the calls are fine.

PS: Your UI is messy, do some homework.
 
Share this answer
 
Comments
nameJulian 30-May-13 3:28am    
I had given up up the default constructor and called the parameterized constructor directrly intro the main method( in the constroctor calling the createInterface method), like this:
public static void main(String...args){
try{

String userName=JOptionPane.showInputDialog(window,"Name: "," ",JOptionPane.PLAIN_MESSAGE);
try{
String serverName="localhost";
new ChatApplication(userName, serverName); //call to appropriate constructor
window.setTitle(userName);
}catch(IOException e){
System.err.println(e.toString());
}

}//main
But i'm still geting the same exception.
AlphaDeltaTheta 30-May-13 3:40am    
Send me your complete class (if you can), I'm really confused at your flow of code...
nameJulian 30-May-13 6:47am    
this is the client class:
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;


public class ChatApplication implements ActionListener{

static JFrame window;
static Socket clientSocket;
Socket serverClientSocket;
BufferedReader input;
PrintWriter output;
static JTextArea messagesTextArea;
static JTextArea usersTextArea;
static JTextField messageField;
JButton sendButton;
JButton connectButton;
JButton startServerButton;
String userName=new String();
static boolean sendFlag=false;


public ChatApplication(){}

public ChatApplication(String userName,String serverName) throws UnknownHostException, IOException{
this.userName=userName;
clientSocket=new Socket(serverName,9999);
input=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
output=new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()),true);
output.println(userName);
createInterface();
new ServerMessageThread().start();
}

public void createInterface(){
window=new JFrame();
window.setSize(600,600);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new BoxLayout(window.getContentPane(),BoxLayout.Y_AXIS));

sendButton=new JButton("Send");
connectButton=new JButton("Connect");
startServerButton=new JButton("Start");

messageField=new JTextField(10);
messagesTextArea=new JTextArea(40,40);
messagesTextArea.setEditable(false);
usersTextArea=new JTextArea(40,10);
usersTextArea.setEditable(false);

JScrollPane scrollPane=new JScrollPane(messagesTextArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

JPanel initialPanel=new JPanel();
initialPanel.setLayout(new BoxLayout(initialPanel,BoxLayout.X_AXIS));
initialPanel.add(connectButton);
initialPanel.add(startServerButton);

JPanel upPanel=new JPanel();
upPanel.setLayout(new BoxLayout(upPanel,BoxLayout.X_AXIS));
upPanel.setBorder(new TitledBorder(""));
upPanel.add(scrollPane);
upPanel.add(usersTextArea);

JPanel bottomPanel=new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel,BoxLayout.X_AXIS));
bottomPanel.setBorder(new TitledBorder(""));
bottomPanel.add(messageField);
bottomPanel.add(sendButton);

window.add(initialPanel);
window.add(upPanel);
window.add(bottomPanel);

sendButton.addActionListener(this);

// connectButton.addActionListener(new ActionListener(){
//
// public void actionPerformed(ActionEvent e){
//
// String userName=JOptionPane.showInputDialog(window,"Name: "," ",JOptionPane.PLAIN_MESSAGE);
// try{
// String serverName="localhost";
// new ChatApplication(userName, serverName);
// window.setTitle(userName);
//
// }catch(IOException ex){
// JOptionPane.showMessageDialog(window,"Clientul nu se poate conecta."+ex.getMessage().toString());
// }
//
// }
//
// });

startServerButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){
Thread thread=new Thread(){
public void run(){

ChatServer server=new ChatServer();
try {
server.process();
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
};

thread.start();


}

});

}

public static void main(String[] args) {

//ChatApplication
nameJulian 30-May-13 6:54am    
and the continuity:

public static void main(String[] args) {

//ChatApplication program=new ChatApplication();
//program.createInterface();
SwingUtilities.invokeLater(new Runnable(){
public void run(){
String userName=JOptionPane.showInputDialog(window,"Name: "," ",JOptionPane.PLAIN_MESSAGE);
try{
String serverName="localhost";
new ChatApplication(userName, serverName);
window.setTitle(userName);

}catch(IOException ex){
JOptionPane.showMessageDialog(window,"Clientul nu se poate conecta."+ex.getMessage().toString());
}
}

});
}


public void actionPerformed(ActionEvent e) {

if(e.getSource()==sendButton){
sendFlag=true;

try{
String messageToServer=new String("");
messageToServer=messageField.getText();

output.println(messageToServer);
messageField.setText("");

}catch(NullPointerException ex){
System.err.println(ex.getMessage());
ex.printStackTrace();
}
}
}



/*
* clasa se ocupa cu crearea unui thread pentru a putea citi de la server
*/

class ServerMessageThread extends Thread{


public void run(){

String serverResponse=new String();

try {
while(true){
serverResponse=input.readLine();
messagesTextArea.append(serverResponse+"\n");
}
} catch (IOException e) {
messagesTextArea.setForeground(Color.RED);
messagesTextArea.setText("Eroare citire de la server: "+e.getMessage());
}
}
}

/*
* clasa care se ocupa cu crearea firelor de executie a clientilor
*/

}
AlphaDeltaTheta 30-May-13 7:52am    
K thanks... I'm running it to see

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900