java 设置 JFileChooser 打开当前目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7780892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:25:48  来源:igfitidea点击:

set the JFileChooser to open current directory

javafileswingjfilechooser

提问by Tofiq

I created a JFileChooser to open a file, but when I select a file and open it,for second the time that i want to select a file, the JFileChooser is not in the current directory. How set the JFileChooser to open the current directory?

我创建了一个 JFileChooser 来打开一个文件,但是当我选择一个文件并打开它时,第二次我想选择一个文件时,JFileChooser 不在当前目录中。如何设置 JFileChooser 打开当前目录?

JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
         fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
         int result = fileChooser.showOpenDialog( this );
         if ( result == JFileChooser.APPROVE_OPTION ){
              File fileName = fileChooser.getSelectedFile();
              File path=fileChooser.getCurrentDirectory();
              if ( ( fileName == null ) || ( fileName.getName().equals( "" ) ) )
              {
                 JOptionPane.showMessageDialog( this, "Invalid File Name",
                    "Invalid File Name", JOptionPane.ERROR_MESSAGE );
              }
              else{
               currentPath=path.getPath()+"\"+fileName.getName();}
             } 

回答by jefflunt

Either pass the directory into the constructorvia the Fileparameter (a Filecan also be a directory, FYI), or use the .setCurrentDirectory(File dir)method before you make the JFileChooser visible.

通过参数将目录传递给构造File函数(aFile也可以是目录,仅供参考),或者.setCurrentDirectory(File dir)在使 JFileChooser 可见之前使用该方法。

Also, to make the JFileChooser stay in the same folder, you need to save the folder of the file/directory chosen from last time, and use THAT value to control which folder it starts in the subsequent times via .setCurrentDirectory(File dir)

另外,为了让 JFileChooser 留在同一个文件夹中,您需要保存上次选择的文件/目录的文件夹,并使用 THAT 值控制它在后续时间启动的文件夹 .setCurrentDirectory(File dir)

回答by Andrew Thompson

Make the chooser a class level attribute and create it only once. That way, it not only points to where it did when closed, but will have the same size, location, file filter selected etc.

使选择器成为类级别属性,并且只创建一次。这样,它不仅指向关闭时的位置,而且将具有相同的大小、位置、选择的文件过滤器等。