S
S
smcopandakun2014-08-09 18:01:26
Java
smcopandakun, 2014-08-09 18:01:26

Threads, NullPointerException, Java, WHAT?

Hello I need to write a "chat" in Java using threads and a GUI. I'm not strong in either.

private class Receiver  implements Runnable{
        /**
         * run() вызовется после запуска нити из конструктора клиента чата.
         */

        public void run() {
            while (!s.isClosed()) { //сходу проверяем коннект.
                String line = null;
                try {
                    line = socketReader.readLine(); // пробуем прочесть
    } catch (IOException e) { // если в момент чтения ошибка, то...
        // проверим, что это не банальное штатное закрытие сокета сервером
        if ("Socket closed".equals(e.getMessage())) {
            break;
        }
        System.out.println("Connection lost"); // а сюда мы попадем в случае ошибок сети.
        close(); // ну и закрываем сокет (кстати, вызвается метод класса ChatClient, есть доступ)
    }
    if (line == null) {  // строка будет null если сервер прикрыл коннект по своей инициативе, сеть работает
        System.out.println("Server has closed connection");
        close(); // ...закрываемся
    } else { // иначе печатаем то, что прислал сервер.
        System.out.println("Server:" + line);       
    }
}
}

The console version works great, but... my knowledge is running out. Next, I need to fill in the TextArea that NetBeans generated for me. For some reason, I'm ashamed of the next line that I'm adding here.
else { // иначе печатаем то, что прислал сервер.
        jChatBox.setText(jChatBox.getText() + line)      
    }

I don't know what mistake I made, but I think it's very stupid. As a result, I get NullPointerExeption on the same line.
Please tell me how to solve this problem. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FoxInSox, 2014-08-09
@FoxInSox

jChatBox == null
I can't understand the reasons from the code you provided.

F
FanKiLL, 2014-08-09
@FanKiLL

Firstly, check if the TextArea is not set setEditable(false);
. Secondly, the TextArea has a method appendthat will add text to the existing one.
In this case, the construction jChatBox.setText(jChatBox.getText() + line)is not needed, change to appendplus, I hope you add to the lines, "\n"
otherwise it will be a mess.
Thirdly, read how to work with TextArea everything is a little different there than with ordinary text controls
Xs, what else to write ... Without code, it's hard to say why null. And in general, what exactly is the null TextArea or line that you pass there? Little info.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question