2012-08-12 124 views
1

嗨我試圖用java程序打開word文件。該計劃給了我下面的錯誤」在Java中使用默認程序打開文件的問題

Cannot make a static reference to the non-static method open(File) from the type Desktop 

我不知道如何解決這個問題。能否請您幫助我。謝謝。下面是代碼片段。

@Override 
public void actionPerformed(ActionEvent e) { 
    List<File> files; 
    File startingDirectory = new File("C:/Hello/"); 
    try { 
     files = getFileListing(startingDirectory); 
     for (File file : files){ 
      Desktop.open(file); 
     } 

    } catch (FileNotFoundException ex) { 
     System.out.println("File Not Found"); 
} 

回答

1

嘗試

Desktop.getDesktop().open(file); 

改爲

您還應該檢查Desktop.isDekstopSupported以確保功能ITY要嘗試執行存在

+0

它工作。感謝束 – Pavel 2012-08-12 23:44:21

+0

很高興有一個簡單的問題,以改變;)很高興成爲協助 – MadProgrammer 2012-08-12 23:47:05

1

您需要首先實例化一個Desktop對象,像這樣:

Desktop d = Desktop.getDesktop(); 

,你可以調用桌面對象的實例方法,這樣以後:

d.open(file); 

在代碼中,你試圖調用實例上方法open()Desktop,這將無法正常工作。唯一可以在類中調用的方法是static方法,所有其他方法需要在相應類的實例上調用。

相關問題