欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java Swing组件JFileChooser用法实例分析

程序员文章站 2024-04-01 22:10:22
本文实例讲述了java swing组件jfilechooser用法。分享给大家供大家参考,具体如下: jfilechooser文件选择器是swing中经常用到的一个控件。...

本文实例讲述了java swing组件jfilechooser用法。分享给大家供大家参考,具体如下:

jfilechooser文件选择器是swing中经常用到的一个控件。它的使用主要包含以下几个参数:

1.当前路径。也就是它第一次打开时所在的路径,许多软件喜欢设置为桌面。

2.文件过滤器。通过设置文件过滤器,只有特定类型的文件是可见的,比如文本,音频,等。

3.选择模式。包含三种情况:仅文件, 仅目录, 文件或目录。

4.是否允许多选。

jfilechooser的参数当然不止以上4种,它还有很多高级选项,比如你可以对文件的显示图标进行定制等,由于不经常用,这里不再介绍。

有2个地方要注意:

1.文件过滤器建议使用filenameextensionfilter,它是filefilter的子类,以非常方便的方法实现了过滤器。用法见代码。

2.getselectedfiles()方法,它只在ismultiselectionenable()方法返回true是有效。也就是说,如果你不允许多选,则只能使用getselectedfile()方法,否则只能得到一个空的文件列表。

下面通过一个demo来展示它的基本用法。

package awtdemo;
import java.io.file;
import javax.swing.jfilechooser;
import javax.swing.joptionpane;
import javax.swing.filechooser.filenameextensionfilter;
import javax.swing.filechooser.filesystemview;
/**
 *
 * @author pzy
 */
@suppresswarnings("serial")
public class jfilechooserframe extends javax.swing.jframe {
  /**
   * creates new form jfilechooserframe
   */
  public jfilechooserframe() {
    initcomponents();
  }
  /**
   * this method is called from within the constructor to initialize the form.
   * warning: do not modify this code. the content of this method is always
   * regenerated by the form editor.
   */
  @suppresswarnings({ "unchecked", "rawtypes" })
  // <editor-fold defaultstate="collapsed" desc="generated code">
  private void initcomponents() {
    filefilterisbg = new javax.swing.buttongroup();
    ismultiselectbg = new javax.swing.buttongroup();
    jpanel1 = new javax.swing.jpanel();
    text_rb = new javax.swing.jradiobutton();
    video_rb = new javax.swing.jradiobutton();
    audio_rb = new javax.swing.jradiobutton();
    all_rb = new javax.swing.jradiobutton();
    jpanel2 = new javax.swing.jpanel();
    jcombobox1 = new javax.swing.jcombobox();
    multiselect_rb = new javax.swing.jradiobutton();
    singleselect_rb = new javax.swing.jradiobutton();
    jpanel3 = new javax.swing.jpanel();
    jbutton1 = new javax.swing.jbutton();
    setdefaultcloseoperation(javax.swing.windowconstants.exit_on_close);
    setlocationbyplatform(true);
    jpanel1.setborder(javax.swing.borderfactory.createtitledborder("文件类型"));
    filefilterisbg.add(text_rb);
    text_rb.settext("文本");
    filefilterisbg.add(video_rb);
    video_rb.settext("视频");
    filefilterisbg.add(audio_rb);
    audio_rb.settext("音频");
    filefilterisbg.add(all_rb);
    all_rb.setselected(true);
    all_rb.settext("所有");
    javax.swing.grouplayout jpanel1layout = new javax.swing.grouplayout(jpanel1);
    jpanel1.setlayout(jpanel1layout);
    jpanel1layout.sethorizontalgroup(
      jpanel1layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(javax.swing.grouplayout.alignment.trailing, jpanel1layout.createsequentialgroup()
        .addcontainergap(javax.swing.grouplayout.default_size, short.max_value)
        .addcomponent(text_rb)
        .addgap(29, 29, 29)
        .addcomponent(video_rb)
        .addgap(35, 35, 35)
        .addcomponent(audio_rb)
        .addgap(39, 39, 39)
        .addcomponent(all_rb)
        .addgap(32, 32, 32))
    );
    jpanel1layout.setverticalgroup(
      jpanel1layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(jpanel1layout.createsequentialgroup()
        .addcontainergap()
        .addgroup(jpanel1layout.createparallelgroup(javax.swing.grouplayout.alignment.baseline)
          .addcomponent(video_rb)
          .addcomponent(text_rb)
          .addcomponent(audio_rb)
          .addcomponent(all_rb))
        .addcontainergap(javax.swing.grouplayout.default_size, short.max_value))
    );
    jpanel2.setborder(javax.swing.borderfactory.createtitledborder("选择模式"));
    jcombobox1.setmodel(new javax.swing.defaultcomboboxmodel(new string[] { "仅文件", "仅目录", "文件或目录" }));
    jcombobox1.addactionlistener(new java.awt.event.actionlistener() {
      public void actionperformed(java.awt.event.actionevent evt) {
        jcombobox1actionperformed(evt);
      }
    });
    ismultiselectbg.add(multiselect_rb);
    multiselect_rb.settext("可多选");
    ismultiselectbg.add(singleselect_rb);
    singleselect_rb.setselected(true);
    singleselect_rb.settext("不可多选");
    javax.swing.grouplayout jpanel2layout = new javax.swing.grouplayout(jpanel2);
    jpanel2.setlayout(jpanel2layout);
    jpanel2layout.sethorizontalgroup(
      jpanel2layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(jpanel2layout.createsequentialgroup()
        .addcontainergap()
        .addcomponent(jcombobox1, javax.swing.grouplayout.preferred_size, 144, javax.swing.grouplayout.preferred_size)
        .addgap(18, 18, 18)
        .addcomponent(multiselect_rb, javax.swing.grouplayout.preferred_size, 82, javax.swing.grouplayout.preferred_size)
        .addgap(18, 18, 18)
        .addcomponent(singleselect_rb, javax.swing.grouplayout.preferred_size, 82, javax.swing.grouplayout.preferred_size)
        .addcontainergap(14, short.max_value))
    );
    jpanel2layout.setverticalgroup(
      jpanel2layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(jpanel2layout.createsequentialgroup()
        .addcontainergap()
        .addgroup(jpanel2layout.createparallelgroup(javax.swing.grouplayout.alignment.baseline)
          .addcomponent(jcombobox1, javax.swing.grouplayout.preferred_size, javax.swing.grouplayout.default_size, javax.swing.grouplayout.preferred_size)
          .addcomponent(multiselect_rb)
          .addcomponent(singleselect_rb))
        .addcontainergap(16, short.max_value))
    );
    jbutton1.settext("开始");
    jbutton1.addactionlistener(new java.awt.event.actionlistener() {
      public void actionperformed(java.awt.event.actionevent evt) {
        jbutton1actionperformed(evt);
      }
    });
    javax.swing.grouplayout jpanel3layout = new javax.swing.grouplayout(jpanel3);
    jpanel3.setlayout(jpanel3layout);
    jpanel3layout.sethorizontalgroup(
      jpanel3layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(jpanel3layout.createsequentialgroup()
        .addgap(117, 117, 117)
        .addcomponent(jbutton1, javax.swing.grouplayout.preferred_size, 139, javax.swing.grouplayout.preferred_size)
        .addcontainergap(javax.swing.grouplayout.default_size, short.max_value))
    );
    jpanel3layout.setverticalgroup(
      jpanel3layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(jpanel3layout.createsequentialgroup()
        .addgap(26, 26, 26)
        .addcomponent(jbutton1, javax.swing.grouplayout.preferred_size, 32, javax.swing.grouplayout.preferred_size)
        .addcontainergap(19, short.max_value))
    );
    javax.swing.grouplayout layout = new javax.swing.grouplayout(getcontentpane());
    getcontentpane().setlayout(layout);
    layout.sethorizontalgroup(
      layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(layout.createsequentialgroup()
        .addcontainergap()
        .addgroup(layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
          .addcomponent(jpanel1, javax.swing.grouplayout.default_size, javax.swing.grouplayout.default_size, short.max_value)
          .addcomponent(jpanel2, javax.swing.grouplayout.default_size, javax.swing.grouplayout.default_size, short.max_value)
          .addgroup(layout.createsequentialgroup()
            .addcomponent(jpanel3, javax.swing.grouplayout.default_size, javax.swing.grouplayout.default_size, short.max_value)
            .addgap(84, 84, 84)))
        .addcontainergap())
    );
    layout.setverticalgroup(
      layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(layout.createsequentialgroup()
        .addgap(8, 8, 8)
        .addcomponent(jpanel1, javax.swing.grouplayout.preferred_size, javax.swing.grouplayout.default_size, javax.swing.grouplayout.preferred_size)
        .addgap(18, 18, 18)
        .addcomponent(jpanel2, javax.swing.grouplayout.preferred_size, javax.swing.grouplayout.default_size, javax.swing.grouplayout.preferred_size)
        .addgap(18, 18, 18)
        .addcomponent(jpanel3, javax.swing.grouplayout.preferred_size, javax.swing.grouplayout.default_size, javax.swing.grouplayout.preferred_size)
        .addcontainergap(javax.swing.grouplayout.default_size, short.max_value))
    );
    pack();
  }// </editor-fold>
  private void jcombobox1actionperformed(java.awt.event.actionevent evt) {
    // todo add your handling code here:
    string itemstring = jcombobox1.getselecteditem().tostring();
    if ("仅文件".equals(itemstring)) {
      fileselectionmode = jfilechooser.files_only;
    } else if ("仅目录".equals(itemstring)) {
      fileselectionmode = jfilechooser.directories_only;
    } else if ("文件或目录".equals(itemstring)) {
      fileselectionmode = jfilechooser.files_and_directories;
    }
  }
  private void jbutton1actionperformed(java.awt.event.actionevent evt) {
    // todo add your handling code here:
    filechooser = new jfilechooser();
    //初始化当前路径
    filesystemview fsv = filesystemview.getfilesystemview();
    file homefile =fsv.gethomedirectory();  //这便是读取桌面路径的方法了
    filechooser.setcurrentdirectory(homefile);
    //初始化文件过滤器
    if (text_rb.isselected()) {
      filter = new filenameextensionfilter("文本文件", "log", "txt");
      filechooser.setfilefilter(filter);
    }
    if (video_rb.isselected()) {
      filter = new filenameextensionfilter("视频文件", "mp4", "mkv");
      filechooser.setfilefilter(filter);
    }
    if (audio_rb.isselected()) {
      filter = new filenameextensionfilter("音频文件", "mp3", "wma");
      filechooser.setfilefilter(filter);
    }
    //初始化选择模式
    filechooser.setfileselectionmode(fileselectionmode);
    //是否允许多选
    if (multiselect_rb.isselected()) {
      filechooser.setmultiselectionenabled(true);
    }
    else if(singleselect_rb.isselected()) {
      filechooser.setmultiselectionenabled(false);
    }
    //打开文件选择器
    int i = filechooser.showdialog(this, "选择");
    if(i == jfilechooser.approve_option){
      stringbuilder sb;
      if(filechooser.ismultiselectionenabled()){
      sb = new stringbuilder("您选择了以下文件:");
      file [] files = filechooser.getselectedfiles();
      for (file file : files) {
        sb.append("\n");
        sb.append(file.getname());
      }
      }
      else{
        file file = filechooser.getselectedfile();
        sb = new stringbuilder("您选择的文件是:");
         sb.append("\n");
        sb.append(file.getname());
      }
      joptionpane.showmessagedialog(this, sb);
    }
  }
  /**
   * @param args the command line arguments
   */
  public static void main(string args[]) {
    /* set the nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" look and feel setting code (optional) ">
    /* if nimbus (introduced in java se 6) is not available, stay with the default look and feel.
     * for details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
      for (javax.swing.uimanager.lookandfeelinfo info : javax.swing.uimanager.getinstalledlookandfeels()) {
        if ("nimbus".equals(info.getname())) {
          javax.swing.uimanager.setlookandfeel(info.getclassname());
          break;
        }
      }
    } catch (classnotfoundexception ex) {
      java.util.logging.logger.getlogger(jfilechooserframe.class.getname()).log(java.util.logging.level.severe, null, ex);
    } catch (instantiationexception ex) {
      java.util.logging.logger.getlogger(jfilechooserframe.class.getname()).log(java.util.logging.level.severe, null, ex);
    } catch (illegalaccessexception ex) {
      java.util.logging.logger.getlogger(jfilechooserframe.class.getname()).log(java.util.logging.level.severe, null, ex);
    } catch (javax.swing.unsupportedlookandfeelexception ex) {
      java.util.logging.logger.getlogger(jfilechooserframe.class.getname()).log(java.util.logging.level.severe, null, ex);
    }
    //</editor-fold>
    /* create and display the form */
    java.awt.eventqueue.invokelater(new runnable() {
      public void run() {
        new jfilechooserframe().setvisible(true);
      }
    });
  }
  private jfilechooser filechooser;
  private filenameextensionfilter filter;
  private int fileselectionmode = jfilechooser.files_only;
  // variables declaration - do not modify
  private javax.swing.jradiobutton all_rb;
  private javax.swing.jradiobutton audio_rb;
  private javax.swing.buttongroup filefilterisbg;
  private javax.swing.buttongroup ismultiselectbg;
  private javax.swing.jbutton jbutton1;
  @suppresswarnings("rawtypes")
 private javax.swing.jcombobox jcombobox1;
  private javax.swing.jpanel jpanel1;
  private javax.swing.jpanel jpanel2;
  private javax.swing.jpanel jpanel3;
  private javax.swing.jradiobutton multiselect_rb;
  private javax.swing.jradiobutton singleselect_rb;
  private javax.swing.jradiobutton text_rb;
  private javax.swing.jradiobutton video_rb;
  // end of variables declaration
}

运行效果如下:

Java Swing组件JFileChooser用法实例分析

Java Swing组件JFileChooser用法实例分析

Java Swing组件JFileChooser用法实例分析

更多关于java相关内容感兴趣的读者可查看本站专题:《java数据结构与算法教程》、《java字符与字符串操作技巧总结》、《java操作dom节点技巧总结》、《java文件与目录操作技巧汇总》和《java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。