2017-06-21 143 views
0

我不知道代碼有什麼問題。你能幫我弄清楚嗎?爲什麼我的文件選擇器不打開對話框

private void doOpenFile() { 
    int result = myFileChooser.showOpenDialog(this); 

    if (result == JFileChooser.APPROVE_OPTION) { 
     Path path = myFileChooser.getSelectedFile().toPath(); 

     try { 
      String contentString = ""; 

      for (String s : Files.readAllLines(path, StandardCharsets.UTF_8)) { 
       contentString += s; 
      } 

      jText.setText(contentString); 

     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
} 

private void doSaveFile() { 
    int result = myFileChooser.showSaveDialog(this); 

    if (result == JFileChooser.APPROVE_OPTION) { 
     // We'll be making a mytmp.txt file, write in there, then move it to 
     // the selected 
     // file. This takes care of clearing that file, should there be 
     // content in it. 
     File targetFile = myFileChooser.getSelectedFile(); 

     try { 
      if (!targetFile.exists()) { 
       targetFile.createNewFile(); 
      } 

      FileWriter fw = new FileWriter(targetFile); 

      fw.write(jText.getText()); 
      fw.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+1

[你得到了什麼錯誤/異常](// stackoverflow.com/help/mcve)?有關這方面的細節將確實幫助我們診斷問題。 –

+0

通過多次寫相同的問題不會給你答案。您需要提供更多關於實際得到的輸出或錯誤的詳細信息。 –

回答

0

我不知道你怎麼用你的myFileChooser和你怎麼實例化他們,但這些代碼工作得很好:

public class ForTestApplication { 


    public static void main(String[] args) { 

    Window window = new Window(); 

    window.setVisible(true); 

    window.showFileChooser(); 

    } 


    static class Window extends JFrame { 

    JFileChooser jFileChooser = new JFileChooser(); 

    public void showFileChooser() { 

     jFileChooser.showDialog(this, "Just for test"); 

    } 

    } 

} 

下面是截圖:enter image description here

請提供更多代碼來找出發生了什麼。

相關問題