I made an instant messenger at first using a JTextArea called chatWindow. I changed it to a JTextPane later on. After adding my styling attributes, I got a null pointer exception in the console of eclipse. Here is my code for the constructor and methods class:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Server extends JFrame{
private JTextField userText;
private JTextPane chatWindow;
StyledDocument doc = chatWindow.getStyledDocument();
//Defining attributes to varibles (keyword)
SimpleAttributeSet keyWord = new SimpleAttributeSet();
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
//constructor
public Server(){
super("Mikey Mac Instant Messenger");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText, BorderLayout.NORTH);
chatWindow = new JTextPane();
chatWindow.setBackground(Color.getHSBColor(207, 24, 87));
add(new JScrollPane(chatWindow));
setSize(850,600);
setVisible(true);
}
//set up and run the server
public void startRunning(){
try{
server = new ServerSocket(6789, 100);
while(true){
try{
waitForConnection();
setupStreams();
whileChatting();
}catch(EOFException eofException){
showMessage("\n SYSTEM - Server ended the connection!");
}finally{
closeWindow();
}
}
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//wait for connection, then display connection information
private void waitForConnection() throws IOException{
chatWindow.setEditable(false);
showMessage("SYSTEM - Waiting for someone to connect... \n");
connection = server.accept();
showMessage("SYSTEM - Now connected to " + connection.getInetAddress().getHostName());
}
//get stream to send and recieve data
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n SYSTEM - Streams are now setup! \n");
}
//during the chat conversation
private void whileChatting() throws IOException{
String message = " SYSTEM - You are now connected!";
sendMessage(message);
ableToType(true);
do{
//have a conversation
try{
message = (String) input.readObject();
showMessage("\n" + message);
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n SYSTEM - I have no clue what the user just said!");
}
}while(!message.equals("CLIENT - END"));
}
//close streams and sockets after you are done chatting
private void closeWindow(){
showMessage("\n SYSTEM - Closing Connections... \n");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send message to client
private void sendMessage(String message){
try{
output.writeObject("SERVER - " + message);
output.flush();
showMessage("\nSERVER - " + message);
}catch(IOException ioException){
//chatWindow.append("\n System Error: Dude I can't send this...");
try
{
StyleConstants.setForeground(keyWord, Color.getHSBColor(351, 95, 95));
StyleConstants.setBackground(keyWord, Color.YELLOW);
StyleConstants.setBold(keyWord, true);
doc.insertString(0, "System Error: Dude, I can't send this...", keyWord );
}
catch(Exception e) { System.out.println(e); }
}
}
//updates chatWindow
private void showMessage(final String string){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
//chatWindow.append(string);
//THE BOTTOM METHOD IS USED FOR APPENDING A STRING JTEXTPANE STYLE HAHA
try
{
//doc.insertString(0, "Start of text\n", null );
//doc.insertString(doc.getLength(), "", string );
//doc.insertString(int offset, String str, ArributeSet a);
//SETTING THE STYLE FOR THE STRING (down below)
StyleConstants.setForeground(keyWord, Color.getHSBColor(251, 89, 87));
//StyleConstants.setBackground(keyWord, Color.YELLOW);
StyleConstants.setBold(keyWord, false);
doc.insertString(0, string, keyWord);
}
catch(Exception e) { System.out.println(e); }
}
}
);
}
//let the user type stuff into their box
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
}
And here is my code for the main method class:
import javax.swing.JFrame;
public class ServerTest {
public static void main(String[] args) {
Server messaging = new Server();
messaging.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
messaging.startRunning();
}
}
I am getting my null pointer exception in 2 spots:
- The first one is here (In constructor):
**`StyledDocument doc = chatWindow.getStyledDocument();`**
- The second one is here (In main):
**`Server messaging = new Server();`**
Here is what the message saids in my console:
Exception in thread "main" java.lang.NullPointerException
at Server.<init>(Server.java:18)
at ServerTest.main(ServerTest.java:6)
Does anyone know how I could solve this null pointer exception error? Thanks.
Is because you never initialized
chatWindow. Move the above initialization code into your constructor and it should be fine. You will need to keep the member variable declaration of:so that you can reference it later. To quote from the comments: