设置 JFileChooser 打开当前目录
我创建了一个 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();}
}
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 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();}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将选择器设为类级别属性并仅创建一次。这样,它不仅指向关闭时的位置,而且具有相同的大小、位置、选择的文件过滤器等。
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.
将目录传递到 构造函数< /a> 通过
File
参数(File
也可以是目录,仅供参考),或使用.setCurrentDirectory(File dir)
方法在使 JFileChooser 可见之前。另外,要使 JFileChooser 保留在同一文件夹中,您需要保存上次选择的文件/目录的文件夹,并使用该值通过
.setCurrentDirectory(File目录)
Either pass the directory into the constructor via the
File
parameter (aFile
can also be a directory, FYI), or use the.setCurrentDirectory(File dir)
method before you make the JFileChooser visible.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)