将JFileChooser设置为打开当前目录。

8

我创建了一个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();}
             } 
2个回答

12

你可以通过将目录传递给构造函数中的File参数(注意,File也可以是一个目录),或在让JFileChooser可见之前使用.setCurrentDirectory(File dir)方法来设置目录。

另外,为了使JFileChooser停留在同一文件夹中,您需要保存上次选择的文件/目录的文件夹,并使用该值来控制下一次启动时它开始的文件夹,方法是使用.setCurrentDirectory(File dir)


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接