0

Имеется класс с несколькими методами:

public class StartAndGo implements Runnable{   
    public JTextArea infArea;

    private void startPoolThreads(int countThreads){
        int countCore = Runtime.getRuntime().availableProcessors();
        if((countThreads<0) || (countThreads>countCore)){
            appendInTextArea("Enter the number of threads from 1 to "+countCore); //Первый вызов метода
        }else{
            StartAndGo theJob = new StartAndGo();
            for(int i=0;i<countThreads;i++){
                Thread t = new Thread(theJob);
                t.start();
            }
        }
    }

    private void getIPAddresses(){
        appendInTextArea("Getting IP-addresses from file..."); //Второй вызов метода
        ...
    }

    synchronized void appendInTextArea(String t){
        infArea.append(t);
    }
}

Метод appendInTextArea добавляет текстовое сообщение в текстовое поле на форме. Так вот, при вызове метода appendInTextArea из метода startPoolThreads - текстовое сообщение добавляется в текстовое поле, а при вызове из getIPAddresses - исключение:

Exception in thread "Thread-2" java.lang.NullPointerException
    at com.parse.webdriver.StartAndGo.appendInTextArea(StartAndGo.java:134)
    at com.parse.webdriver.StartAndGo.getIPAddresses(StartAndGo.java:86)
    at com.parse.webdriver.StartAndGo.run(StartAndGo.java:39)
    at java.lang.Thread.run(Thread.java:745)

Инициализация infArea, метод buildGUI находится в классе StartAndGo:

private void buildGUI(){
        ...     
        infArea = new JTextArea(3,25);
        infArea.setLineWrap(true);
        infArea.setWrapStyleWord(true);

        JScrollPane scroller = new JScrollPane(infArea);
        scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        panel.add(scroller);
        ...     
        frame.getContentPane().add(panel);
        frame.setVisible(true);
}

Не могу понять, почему не работает вызов метода во втором случае?

1 ответ 1

3
public class StartAndGo implements Runnable{   
    public JTextArea infArea;

    private void startPoolThreads(int countThreads){
        int countCore = Runtime.getRuntime().availableProcessors();
        if((countThreads<0) || (countThreads>countCore)){
            appendInTextArea("Enter the number of threads from 1 to "+countCore); //Первый вызов метода
        }else{
            StartAndGo theJob = new StartAndGo(); //!!!Создание нового экземпляра StartAndGo
                        //Т.к. это новый объект, у него infArea = null, 
                        //и он ничего не знает о infArea, который Вы создали в main (при вызове buildGUI)
            theJob.infArea = this.infArea; //Соответственно здесь нужно новому экземпляру передать infArea уже созданный 
                        //(либо создайте сами, исходя из требований)
            for(int i=0;i<countThreads;i++){
               Thread t = new Thread(theJob);
                t.start();
            }
        }
    }

    private void getIPAddresses(){
        appendInTextArea("Getting IP-addresses from file..."); //Второй вызов метода
        ...
    }

    synchronized void appendInTextArea(String t){
        infArea.append(t);
    }
}
7
  • Добавил в вопрос инициализацию.
    – Cenzor
    23 ноя 2016 в 6:16
  • 1
    Когда новый объект создается StartAndGo theJob = new StartAndGo(); у него вызывается buildGUI ? или как-то присваивается ему infArea ? 23 ноя 2016 в 6:55
  • в методе main - new StartAndGo().buildGUI(); в buildGUI ActionListener на кнопку стоит, по нажатию которой дёргается метод startPoolThreads
    – Cenzor
    23 ноя 2016 в 7:52
  • В main понятно Вы инициализируете, но у вас в startPoolThreads создание объекта идет, у которого также надо инициализировать infArea (полагаю именно в потоке вы потом и получаете ошибку с null от этого нового объекта) 23 ноя 2016 в 7:56
  • Именно в пототке
    – Cenzor
    23 ноя 2016 в 9:34

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.