【发布时间】:2019-12-06 03:20:48
【问题描述】:
我不知道如何在 JFileChooser 窗口中一次选择多个文件。我认为它已经启用,因为我在 JFileChooser 对象上使用了setMultiSelectionEnabled(true) 方法,但是当我尝试实际选择多个时,我做不到。我尝试了单击和拖动、CTRL 和箭头键/单击、Alt 和箭头键/单击、Shift 和箭头键/单击,但仍然没有运气。我该怎么做?
我创建 JFileChooser 的代码: 仅使用一个文件时,解析方法工作正常。 当在 JFrame 中按下按钮时调用此类。
public class FileChooser implements ActionListener, Runnable
{
private Parser parser = new Parser();
private static File[] selectedFiles;
private static File currentSelected;
private JFileChooser jfc;
public static File getSelectedFile()
{
return currentSelected;
}
public void actionPerformed(ActionEvent actionEvent)
{
new Thread(this).start();
}
public void run()
{
if ( Window.bFG5IsPressed() && Window.bFGAIsPressed() )
{
jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
jfc.setMultiSelectionEnabled(true);
int returnValue = jfc.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION)
{
selectedFiles = jfc.getSelectedFiles();
for (File e : selectedFiles) {
currentSelected = e;
parser.parseAll(e.getAbsolutePath());
}
}
}
else if ( Window.bFG5IsPressed() )
{
jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
int returnValue = jfc.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION)
{
selectedFiles = jfc.getSelectedFiles();
for (File e : selectedFiles) {
currentSelected = e;
parser.parseFG5(e.getAbsolutePath());
}
}
}
else if ( Window.bFGAIsPressed() )
{
jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
int returnValue = jfc.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION)
{
selectedFiles = jfc.getSelectedFiles();
for (File e : selectedFiles) {
currentSelected = e;
parser.parseFGA(e.getAbsolutePath());
}
}
}
else
{
JOptionPane x = new JOptionPane();
x.showMessageDialog(x, "Escolher tipo de arquivo");
x.setLocation(300,300);
x.setVisible(true);
}
}
}
【问题讨论】:
-
什么时候您使用
setMultiSelectionEnabled?请显示minimal reproducible example。 -
@RealSkeptic 我添加了创建 JFrame 的类
-
@JoeyJohnJo 请检查答案中的示例。无论您是否能够选择多个文件,请运行此程序。如果然后将其与您的代码进行比较。如果没有,请告诉我。
-
你不应该创建一个线程。所有 Swing 组件都应在事件调度线程 (EDT) 上更新。侦听器代码确实在 EDT 上执行。因此,您的代码不仅错误,而且更复杂。
-
我会考虑到这一点并从线程中删除文件选择器。谢谢
标签: java swing jframe awt jfilechooser