java :filefilter限制文件类型,如何将Java中的文件选择器限制为特定文件?

这篇博客探讨了如何在Java中使用JFileChooser进行文件过滤。通过设置FileNameExtensionFilter,实现了只显示特定类型的文件,如PDF、MS Office文档和图片。当用户不是管理员时,仅允许选择这些文件类型;如果是管理员,则可以选择所有文件。博客提供了详细的代码示例来说明如何限制和自定义文件选择器的行为。

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:

}

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.

解决方案

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.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值