swing 中通过 FileFilter 实现打开指定格式的文件

今天做到要打开指定格式的文件,在swing 中,这就不像在Winform 中一样了,只要设置一下,但也比较简单
实现过滤

package com.openfile.biz;

import java.io.File;

import javax.swing.filechooser.FileFilter;

/**
*
* @author zengxx
*
*/
public class TxtFileFilter extends FileFilter {

/**
* 重写接收文件方法
* @return true 表示显示出来
* false 表示不显示出来
*/
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
//显示满足条件的文件
return f.getName().endsWith(".txt") || f.getName().endsWith(".java");
}

/**
* 这就是显示在打开框中
*/
public String getDescription() {

return "*.txt,*.java";
}

}


测试类

package com.openfile.ui;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import com.openfile.biz.TxtFileFilter;

public class AppFrame {

private JFrame frame;

/**
* Launch the application
* @param args
*/
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AppFrame window = new AppFrame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the application
*/
public AppFrame() {
createContents();
}

/**
* Initialize the contents of the frame
*/
private void createContents() {
frame = new JFrame();
frame.setTitle("打开指定格式的文件");
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, 510, 191);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final JTextField txtFilePath = new JTextField();
txtFilePath.setBounds(100, 60, 232, 22);
frame.getContentPane().add(txtFilePath);

final JLabel label = new JLabel();
label.setText("文件");
label.setBounds(29, 62, 66, 18);
frame.getContentPane().add(label);

final JButton btnBrower = new JButton();
btnBrower.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
JFileChooser chooser=new JFileChooser();
chooser.setFileFilter(new TxtFileFilter());
int resultVal=chooser.showOpenDialog(null);
if (resultVal==JFileChooser.APPROVE_OPTION) { //点击确定
String filePath=chooser.getSelectedFile().getAbsolutePath();
txtFilePath.setText(filePath);
}
}
});
btnBrower.setText("浏览");
btnBrower.setBounds(363, 57, 106, 28);
frame.getContentPane().add(btnBrower);
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值