我正在尝试制作一个用于选择文件夹的 JFileChooser。在此 FileChooser 中,我希望用户可以选择创建新文件夹,然后选择它。我注意到 JFileChooser“保存”对话框默认有一个“新文件夹”按钮,但在“打开”对话框中没有出现类似的按钮。有谁知道如何将“新文件夹”按钮添加到“打开”对话框?
具体来说,我想将按钮添加到使用以下代码创建的对话框中:
JFrame frame = new JFrame();
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setFileFilter( new FileFilter(){
@Override
public boolean accept(File f) {
return f.isDirectory();
}
@Override
public String getDescription() {
return "Any folder";
}
});
fc.setDialogType(JFileChooser.OPEN_DIALOG);
frame.getContentPane().add(fc);
frame.pack();
frame.setVisible(true);
最佳答案
好的。最后我通过使用“保存”对话框而不是“打开”对话框解决了这个问题。标准保存对话框已经有一个“新文件夹”按钮,但它在顶部还有一个“另存为:”面板,这是我不想要的。我的解决方案是使用标准保存对话框,但隐藏“另存为”面板。
这是保存对话框的代码:
JFrame frame = new JFrame();
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setFileFilter( new FileFilter(){
@Override
public boolean accept(File f) {
return f.isDirectory();
}
@Override
public String getDescription() {
return "Any folder";
}
});
fc.setDialogType(JFileChooser.SAVE_DIALOG);
fc.setApproveButtonText("Select");
frame.getContentPane().add(fc);
frame.setVisible(true);
这部分定位并隐藏“另存为:”面板:
ArrayList<JPanel> jpanels = new ArrayList<JPanel>();
for(Component c : fc.getComponents()){
if( c instanceof JPanel ){
jpanels.add((JPanel)c);
}
}
jpanels.get(0).getComponent(0).setVisible(false);
frame.pack();
最终结果:
编辑
这个解决方案有一个怪癖,如果用户在当前没有选择目录的情况下按下批准按钮,就会出现这个怪癖。在这种情况下,选择器返回的目录将对应于用户正在查看的任何目录,并与(隐藏的)“另存为:”面板中的文本连接。结果目录可能不存在。我用下面的代码处理了这个问题。
File dir = fc.getSelectedFile();
if(!dir.exists()){
dir = dir.getParentFile();
}
关于java - 如何将 "New folder"按钮添加到 JFileChooser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13783808/