2017-06-21 74 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

请提供更多代码来找出发生了什么。

相关问题