我创建了一个 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();}
}
最佳答案
要么将目录传递到the constructor通过 File
参数(File
也可以是目录,仅供引用),或者在制作之前使用 .setCurrentDirectory(File dir)
方法JFileChooser 可见。
另外,为了使JFileChooser保持在同一个文件夹中,您需要保存上次选择的文件/目录的文件夹,并使用该值通过控制后续启动的文件夹。 setCurrentDirectory(文件目录)
关于java - 设置 JFileChooser 打开当前目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7780892/