chatWindow라는 JTextArea를 사용하여 처음 메신저를 만들었습니다. 나중에 JTextPane으로 변경했습니다. 내 스타일 속성을 추가 한 후 Eclipse의 콘솔에서 널 포인터 예외가 발생했습니다. 나는이 개 지점에서 내 널 포인터 예외를 얻고있다null 포인터 예외 문제
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();
}
}
:
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);
}
}
);
}
}
그리고 여기 내 주요 방법 클래스에 대한 코드입니다 : 여기에 생성자와 메소드 클래스 내 코드입니다
Exception in thread "main" java.lang.NullPointerException
at Server.<init>(Server.java:18)
at ServerTest.main(ServerTest.java:6)
: 여기
- The first one is here (In constructor):
**`StyledDocument doc = chatWindow.getStyledDocument();`**
- The second one is here (In main):
**`Server messaging = new Server();`**
는 메시지가 내 콘솔에 saids 것입니다
누구든지이 null 포인터 예외 오류를 해결할 수있는 방법을 알고 있습니까? 감사. 당신이 chatWindow
를 초기화하지 않기 때문에
편집을위한 BalusC,하지만 내 질문에 대한 답변을 알고 계십니까? – user2596934
저는 일반적으로 이런 종류의 자바 문제에 대해서는 관심이 없습니다. 당신은 이미'NullPointerException'이 무엇을 의미하는지 이해하지 못하는 것처럼 질문을 던졌습니다. 특정 객체 참조가 왜 'null'인지에 대해 명시 적으로 묻지 않았습니다. 엄청난 양의 상향 회선을 사용하여 동일한 또는 최소한 하나 또는 두 개의 대답을 말하면서 10 개의 대답을 쉽게 얻을 수 있습니다. – BalusC
널 포인터 예외 오류가 BalusC라는 것을 알고 있습니다. 나는 왜 내 코드에 하나가 있는지 묻고있다. 내가 왜 내 코드가 그 결과를 처음으로 돌려주는 이유인지 이해하지 못한다면 어떻게 "명시 적으로"null인지 물어볼 수 있습니까? – user2596934