我首先使用名爲chatWindow的JTextArea製作了即時通訊工具。之後我將其更改爲JTextPane。添加了我的樣式屬性之後,我在eclipse的控制檯中得到了一個空指針異常。這裏是我的構造函數和方法的類代碼:空指針異常問題
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);
}
}
);
}
}
這裏是我的主要方法類代碼:
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();
}
}
我得到我的空指針異常在2點:
- The first one is here (In constructor):
**`StyledDocument doc = chatWindow.getStyledDocument();`**
- The second one is here (In main):
**`Server messaging = new Server();`**
以下是消息中我的控制檯甾體抗炎藥:
Exception in thread "main" java.lang.NullPointerException
at Server.<init>(Server.java:18)
at ServerTest.main(ServerTest.java:6)
有誰知道我該如何解決這個空指針異常錯誤?謝謝。
BalusC感謝您的編輯,但您是否知道我的問題的答案? – user2596934
我一般對回答這種極其微不足道的Java問題不感興趣。你以這樣的方式問了問題,就好像你已經不明白'NullPointerException'是什麼意思了。你沒有明確地問爲什麼特定的對象引用是'null'。你可以很容易地得到10個答案,並且可以用相當數量的upvotes來告訴同一個或至少一個或兩個答案。 – BalusC
我知道什麼是空指針異常錯誤意味着BalusC。我只是問爲什麼在我的代碼中有一個。如果我不明白爲什麼我的代碼首先將結果返回給我,我怎麼能問爲什麼它「顯式」爲空? – user2596934