gpt4 book ai didi

java - 文件选择器只显示文件,不允许用户创建自己的文件

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:49:20 24 4
gpt4 key购买 nike

按照 oracle 教程,这段代码应该创建一个文件选择器:

public File getFileAddress() {
JFileChooser chooser = new JFileChooser();
//chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
return chooser.getSelectedFile();
}
return null;
}

应该是这样的:

enter image description here

然而,在 Mac 上工作时,我得到了这个: enter image description here

当我想要得到的是这样的: enter image description here

那么我如何用 java 得到我想要的东西,因为它似乎不起作用。

最佳答案

您正在 JFileChooser 上使用 showOpenDialog。为了显示 Save As tetbox,您可能需要使用 showSaveDialog

public File getFileAddress() {
JFileChooser chooser = new JFileChooser();
//chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
return chooser.getSelectedFile();
}
return null;
}

一般来说,当打开一个文件时,你不想让用户创建他们自己的文件,因为如果你决定从它读取,这可能会导致有关 IOExceptions 的复杂化,因此我假设它正在做OpenDialogs 上的选项。

要将 JFileChooser 限制为某些文件类型,您可以使用 FileNameExtensionFilter你只需要放

chooser.setFileFilter(new FileNameExtensionFilter("RTF FIles", ".rtf"));

在您创建 JFileChooser 之后。

要确保此文件类型在保存文件中,您将必须手动修复它,使用一些字符串操作:

String fileName = chooser.getSelectedFile().getAbsolutePath();
if(!fileName.endWith(".rtf"))fileName += ".rtf";
return new File(fileName);

关于java - 文件选择器只显示文件,不允许用户创建自己的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16311036/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com