Java 将JFileChooser设置为打开当前目录
我创建了一个JFileChooser来打开一个文件,但是当我选择一个文件并打开它时,在我想要选择一个文件的第二次,JFileChooser不在当前目录中。 如何设置JFileChooser以打开当前目录Java 将JFileChooser设置为打开当前目录,java,file,swing,jfilechooser,Java,File,Swing,Jfilechooser,我创建了一个JFileChooser来打开一个文件,但是当我选择一个文件并打开它时,在我想要选择一个文件的第二次,JFileChooser不在当前目录中。 如何设置JFileChooser以打开当前目录 JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES ); fileChooser.s
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();}
}
在使JFileChooser可见之前,可以通过
文件
参数将目录传递到(一个文件
也可以是目录,仅供参考),或者使用.setCurrentDirectory(File dir)
方法
此外,要使JFileChooser保持在同一文件夹中,您需要保存上次选择的文件/目录的文件夹,并使用该值通过
,控制它在后续时间启动哪个文件夹。setCurrentDirectory(file dir)
将选择器设置为类级属性,并仅创建一次。这样,它不仅会指向关闭时的位置,而且会选择相同的大小、位置、文件过滤器等