swing applet 文件浏览器

<!--个人使用方法-->

JButton open = new JButton("Browser");
open.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JFileChooser dialog = new JFileChooser();
dialog.showOpenDialog(new JFrame());
File file = dialog.getSelectedFile();
if(file != null){
String temp = file.getPath();
});


<!-- ...-->

下边的
int result = dlg.showOpenDialog(this);

this,当主类继承frame 或者 JFrame 的时候可以使用.


原文地址:http://hi.baidu.com/sowhatliu/blog/item/c57082ce28ee600a92457ecd.html
swing中JFileChooser的用法


1、基本用法

JFileChooser dlg = new JFileChooser();
dlg.setDialogTitle("Open JPEG file");
int result = dlg.showOpenDialog(this); // 打开"打开文件"对话框
// int result = dlg.showSaveDialog(this); // 打"开保存文件"对话框
if (result == JFileChooser.APPROVE_OPTION) {
File file = dlg.getSelectedFile();
...
}


2、自定义FileFilter

JDK没有提供默认的文件过滤器,但提供了过滤器的抽象超类,我们可以继承它。

import javax.swing.filechooser.FileFilter;

public final class PictureFileFilter extends FileFilter {

private String extension;

private String description;

public PictureFileFilter(String extension, String description) {
super();
this.extension = extension;
this.description = description;
}

public boolean accept(File f) {
if (f != null) {
if (f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if (extension != null && extension.equalsIgnoreCase(this.extension)) {
return true;
}
}
return false;
}

public String getDescription() {
return description;
}

private String getExtension(File f) {
if (f != null) {
String filename = f.getName();
int i = filename.lastIndexOf('.');
if (i > 0 && i < filename.length() - 1) {
return filename.substring(i + 1).toLowerCase();
}
}
return null;
}

}


其实主要就是accept(File f)函数。上例中只有一个过滤器,多个过滤器可参考JDK目录中“demo\jfc\FileChooserDemo\src”中的“ExampleFileFilter.java”


3、多选

在基本用法中,设置

c.setMultiSelectionEnabled(true);


即可实现文件的多选。

读取选择的文件时需使用

File[] files = c.getSelectedFiles();


4、选择目录

利用这个打开对话框,不仅可以选择文件,还可以选择目录。

其实,对话框有一个FileSelectionMode属性,其默认值为“JFileChooser.FILES_ONLY”,只需要将其修改为“JFileChooser.DIRECTORIES_ONLY”即可。

JFileChooser c = new JFileChooser();
c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
c.setDialogTitle("Select path to save");
int result = c.showOpenDialog(PrintDatetime.this);
if (result == JFileChooser.APPROVE_OPTION) {
String path = c.getSelectedFile().getAbsolutePath());
...
}


source: http://www.cppblog.com/justin-shi/archive/2008/08/08/58297.aspx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值