【发布时间】:2013-03-28 18:41:34
【问题描述】:
我将简要解释一下我正在做的事情,然后提供一些我的代码。
我有一个小的 GUI,我在其中选择 JComboBox 上的一个选项,然后单击一个按钮,该按钮将打开一个 JFileChooser,它应该根据 JComboBox 中的选择过滤掉文件。
例如,用户从 JComboBox 中选择Text File,当用户单击该按钮时,它将打开仅显示目录和文本文件的 JFileChooser。
在我的主类中,我在构造函数中有这个:
public MyApp() {
//init components and other logic
comboBox.setModel(new FileExtensionModel());
}
然后在那个类中我有打开文件选择器的按钮的方法:
private void openFilAction(ActionEvent e) {
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.getName().endsWith(myFileType) || f.isDirectory();
}
public String getDescription() {
return "myFileType";
}
}
int choose = fc.showOpenDialog(this);
//do logic
}
最后是我对 DefaultComboBoxModel 的基本扩展:
public class FileExtensionModel extends DefaultComboBoxModel {
Map<String, String> selection;
public FileExtensionModel() {
selection = new HashMap<String, String>();
selection.put("Text File", ".txt");
selection.put("Rar File", ".rar");
selection.put("Zip File", ".rar");
selection.put("Tar File", ".tar");
selection.put("Ini File", ".ini");
for(String key : select.keySet()) {
this.addElement(key);
}
}
}
所以我想知道如何将myFileType 替换为我的FileExtensionModel() 中的地图值,因为我无法从我的内部FileFilter() 类中访问它。
欢迎提出任何建议,我不介意稍微移动代码。如果我能在我的 FileExtensionModel 类中处理大部分内容,那就太好了。
【问题讨论】:
标签: java jcombobox jfilechooser filefilter comboboxmodel