开发者

How to get open file popup

开发者 https://www.devze.com 2023-03-07 11:57 出处:网络
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:

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.getSelect开发者_Python百科edFile() ;
    }

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

How should I go about doing this?


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();
 } 
0

精彩评论

暂无评论...
验证码 换一张
取 消