文件选择器演示

来源:互联网 发布:淘宝卖家不评论吗 编辑:程序博客网 时间:2024/05/27 14:13

JFileChooser的简单变化


import java.awt.*;import java.awt.event.*;import java.io.File;import javax.swing.*;public class JFileChooserDemo extends JFrame{private Container container;//设置容器private JFileChooser chooser;//文件选择器private JButton button;//选择文件按钮private JComboBox comboBox;//用于设定文件对话框作用(打开还是保存)public JFileChooserDemo(){super("文件选择器演示");container = getContentPane();//得到容器container.setLayout(new FlowLayout());//设置为流式布局chooser = new JFileChooser();//初始化文件选择器button = new JButton("选择文件");//初始化按钮comboBox = new JComboBox();//初始化组合框comboBox.addItem("打开");comboBox.addItem("保存");container.add(comboBox);container.add(button);button.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){int state;//文件选择器返回状态chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter());//移去所有文件过滤器chooser.addChoosableFileFilter(new MyFileFilter("gif","图像文件"));//增加文件过滤器,接受gif文件if(comboBox.getSelectedIndex() == 0)//组合框为“打开”state = chooser.showOpenDialog(null);//显示打开文件对话框elsestate = chooser.showOpenDialog(null);//显示保存文件对话框File file = chooser.getSelectedFile();//得到选择的文件if(file != null && state ==JFileChooser.APPROVE_OPTION){//选择了文件并点击了打开可保存按钮JOptionPane.showMessageDialog(null, file.getPath());//显示提示信息}else if(state == JFileChooser.CANCEL_OPTION){//点击了撤销按钮JOptionPane.showMessageDialog(null, "退出");//显示提示信息}else if(state == JFileChooser.ERROR_OPTION);JOptionPane.showMessageDialog(null, "错误!");////显示提示信息}});this.setSize(400,300);this.setLocationRelativeTo(null);this.setVisible(true);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}public static void main(String [] args){new JFileChooserDemo();}}

import java.io.File;import javax.swing.filechooser.FileFilter;//文件过滤器public  class MyFileFilter extends FileFilter{String ends;//文件后缀String description;//文件描述文字public MyFileFilter(String ends,String deccription){this.ends = ends;this.description = description;}public boolean accpt(File file){//重载FileFilter中的accept方法if(file.isDirectory())//如果是目录,则返回truereturn true;String fileName = file.getName();//得到文件名称if(fileName.toUpperCase().endsWith(ends.toUpperCase()))//把文件后缀与可接受后缀转成大写后比较return true;elsereturn false;}public String getDescription(){//返回文件描述文字return description;}@Overridepublic boolean accept(File f) {// TODO Auto-generated method stubreturn false;}}


0 0
原创粉丝点击