2011-12-01 281 views
0

我有一個創建如圖所示一個JFileChooser:處理JFileChooser窗口關閉?

JFileChooser chooser = new JFileChooser(); 
int choosen = chooser.showOpenDialog(fileSelector.this); 

if (choosen == JFileChooser.CANCEL_OPTION) { 
    System.out.println("Closed"); 
} 

如果我關閉了窗口進行選擇我的錯誤:

Exception in thread "main" java.lang.NullPointerException 
    at fileSelector.fileSelector(fileSelector.java:32) 
    at createAndControl.main(createAndControl.java:15) 

我想知道正確的方法處理這個問題,我應該在窗口關閉時採取什麼行動來避免這種情況?

TIA

+0

什麼線是造成異常? – unholysampler

+0

什麼是fileselector.java第32行?如果你喜歡,可以參考JFileChooser上的[tutorial](http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html) - 它有一些很好的代碼示例。 – aishwarya

+0

我試過你的代碼,它工作。正如其他人所說的,更多的代碼會很好。 – Anthea

回答

2

我們建議這樣做反過來:

public static void main(String[] args) { 
    SwingUtilities.invokeLater(new Runnable() { 

     @Override 
     public void run() { 
      JFileChooser fc = new JFileChooser(); 
      int returnVal = fc.showOpenDialog(null); 

      if (returnVal == JFileChooser.APPROVE_OPTION) { 
       File file = fc.getSelectedFile(); 
       //This is where a real application would open the file. 
       System.out.println("Opening: " + file.getName() + ".\n"); 
      } else { 
       System.out.println("Open command cancelled by user.\n"); 
      } 
     } 
    }); 
}