在 MATLAB 中,有一个函数可以提示用户选择一个或多个文件 - uigetfile
,还有另一个功能允许用户选择文件夹 - uigetdir
.
我想为用户提供选择文件或文件夹的能力,使用单个窗口,因为这对用户体验很重要试图创造。
到目前为止,我发现使用上述功能的唯一解决方案 1 需要一个额外的步骤,即提前询问用户他们想要选择什么类型的实体,并相应地调用适当的函数——我觉得这很不方便。
那么我怎样才能有一个允许我选择其中一个的对话框呢?
最佳答案
我们可以为此使用 Java 组件,特别是 JFileChooser
,并确保我们为其提供 FILES_AND_DIRECTORIES
选择标志。
%% Select entity:
jFC = javax.swing.JFileChooser(pwd);
jFC.setFileSelectionMode(jFC.FILES_AND_DIRECTORIES);
returnVal = jFC.showOpenDialog([]);
switch returnVal
case jFC.APPROVE_OPTION
fName = string(jFC.getSelectedFile());
case jFC.CANCEL_OPTION
% do something with cancel
case jFC.ERROR_OPTION
% do something with error
otherwise
throw(MException("fileFolderChooser:unsupportedResult", ...
"Unsupported result returned from JFileChooser: " + returnVal + ...
". Please consult the documentation of the current Java version (" + ...
string(java.lang.System.getProperty("java.version")) + ")."));
end
%% Process selection:
switch true % < this is just some trick to avoid if/elseif
case isfolder(fName)
% Do something with folder
case isfile(fName)
% Do something with file
otherwise
throw(MException('fileFolderChooser:invalidSelection',...
'Invalid selection, cannot proceed!'));
end
这会产生一个看起来很熟悉的对话框,如下所示,它完全按预期工作:
JFileChooser
有各种有趣的设置,例如 multi-selection和 showing hidden files/folders ,以及标准设置,如 changing the dialog title , 按钮 texts和 tooltips等。它也可以简单地用作“打开”对话框或“保存”对话框 setting a value .
在 R2018a 上测试,使用 Java 1.8.0_144(java.lang.System.getProperty("java.version")
的输出)。
关于matlab - 制作一个对话框,用户可以在其中选择文件或文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51440968/