今天做到要打开指定格式的文件,在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);
}
}