How to get open file popup

浪子不回头ぞ 提交于 2019-12-22 09:02:26

问题


Right now, I have a set class path, but I want to have an open file pop up and the user chooses which file to open. I've tried JFileChooser, but haven't been successful so far. Here's my code:

public static void main(String[] args) throws IOException {


    JFileChooser chooser = new JFileChooser();

            int returnValue = chooser.showOpenDialog( null ) ;
    if( returnValue == JFileChooser.APPROVE_OPTION ) {
        File file = chooser.getSelectedFile() ;
    }

    // I don't want this to be hard-coded:
    String filePath = "/Users/Bill/Desktop/hello.txt";

How should I go about doing this?


回答1:


I think the problem is the scope of File file.

Try Declaring file outside the if-block.

 File file = null;
 if( returnValue == JFileChooser.APPROVE_OPTION ) {
        file = chooser.getSelectedFile() ;
 }
 if(file != null)
 {
      String filePath = file.getPath();
 } 


来源:https://stackoverflow.com/questions/6091087/how-to-get-open-file-popup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!