有一个类有几种方法:
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 方法将文本消息添加到表单上的文本字段。因此,当从 startPoolThreads 方法调用 appendInTextArea 方法时,文本消息会添加到文本字段,而当从 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 个回答