如何将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个自定义过滤器.
I am 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屋!