如何将java中的文件选择器限制为特定文件 [英] How to restrict file choosers in java to specific files
问题描述
private void openMenuActionPerformed(java.awt.event.ActionEvent evt) {
DBmanager db = new DBmanager();
if (!db.getCurrentUser().equals("Admin")) {
JOptionPane.showMessageDialog(this, "You are Not Allowed to Run Applications");
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF Documents", "pdf"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("MS Office Documents", "docx", "xlsx", "pptx"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));
fileChooser.setAcceptAllFileFilterUsed(false);
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().open(file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} else if (db.getCurrentUser().equals("Admin")) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().open(file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}// TODO add your handling code here:
}
大家好....我试图通过设置 fileChooser.setAcceptAllFileFilterUsed(false)来过滤文件过滤器中的文件;
。 所有文件选项从 FileChooser
中消失,但除非您从PDF文档,ms Office或图像中选择一个选项,否则所有文件仍然可见。我希望只有我的3个自定义打开文件选择器时过滤。
Hi guys....I'm trying to filter files in a file filter by setting fileChooser.setAcceptAllFileFilterUsed(false);
. The "all files" option disappears from the FileChooser
but all files remain visible unless you select an option from PDF documents,ms Office or images.I want to have only my 3 custom filters upon opening the file chooser.
推荐答案
例如,如果您想严格过滤 JFileChooser
显示最常见的图像文件,您可以使用以下内容:
For example, if you want to filter your JFileChooser
to strictly display most commonly found image files, you would use something like this:
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image Files", "jpg", "png", "gif", "jpeg");
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(filter);
第一个参数是描述(在底部选择时显示的内容),第二个参数是非正式的文件扩展名。
The first argument is the description (what gets displayed upon selection at the bottom) and the second argument are the informal file extensions.
这篇关于如何将java中的文件选择器限制为特定文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!