Swing-JFileChooser的使用
JFileChooser文件选择器是Swing中经常用到的一个控件。它的使用主要包含以下几个参数:
1.当前路径。也就是它第一次打开时所在的路径,许多软件喜欢设置为桌面。
2.文件过滤器。通过设置文件过滤器,只有特定类型的文件是可见的,比如文本,音频,等。
3.选择模式。包含三种情况:仅文件, 仅目录, 文件或目录。
4.是否允许多选。
JFileChooser的参数当然不止以上4种,它还有很多高级选项,比如你可以对文件的显示图标进行定制等,由于不经常用,这里不再介绍。
有2个地方要注意:
1.文件过滤器建议使用FileNameExtensionFilter,它是FileFilter的子类,以非常方便的方法实现了过滤器。用法见代码。
2.getSelectedFiles()方法,它只在isMultiSelectionEnable()方法返回true是有效。也就是说,如果你不允许多选,则只能使用getSelectedFile()方法,否则只能得到一个空的文件列表。
下面通过一个demo来展示它的基本用法。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.javacore.swing.JfileChooser; import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView; /**
*
* @author pzy
*/
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")
// <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;
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
}
运行效果如下:
Swing-JFileChooser的使用的更多相关文章
- java swing文件内容检索工具
Java相关技术 - 文件内容检索工具 拿到一个几百M甚至上G的project让你去学习 有时候你会想知道某个关键词是在哪个文件里 比如:spring MVC配置的@RequestMapping,你从 ...
- Java文件选择对话框(文件选择器JFileChooser)的使用:以一个文件加密器为例
文件加密器,操作过程肯定涉及到文件选择器的使用,所以这里以文件加密器为例.下例为我自己写的一个文件加密器,没什么特别的加密算法,只为演示文件选择器JFileChooser的使用. 加密器界面如图: 项 ...
- Java——文件选择框:JFileChooser
import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import j ...
- 黑马程序员_Java基础:多功能小窗口,swing,io,net综合应用
------- android培训.java培训.期待与您交流! ---------- 概念原理的理解,不代表能熟练应用. 如果将多个知识点关联并应用起来,这能加快我们对知识的掌握. 作为一个初学者, ...
- Swing实现文件选择(目录选择)附导出
具体生成工具如图: (1) (2) (3) (4) 源码 : example.java package org.qiailin.jframe; import java.awt.Container; i ...
- 简单的FTP上传下载(java实现 swing界面)
/** *阅读前请自己在win7上建立FTP主机 *具体步骤如:http://jingyan.baidu.com/article/574c5219d466c36c8d9dc138.html * 然后将 ...
- JFileChooser
http://www.cnblogs.com/dyllove98/archive/2012/03/05/2461895.html package swing.choose; import java.a ...
- Java Swing客户端小项目
记录一下两个用java swing写的客户端. 项目1: 关键词:swing jtable 代码如下: 1.主类: package com.my.agent.client; import java. ...
- SWING中文件的上传
<pre name="code" class="java">import java.io.File; import java.io.FileInpu ...
- Java核心技术卷一基础知识-第9章-Swing用户界面组件-读书笔记
第9章 Swing用户界面组件 本章内容: * Swing与模型-视图-控制器设计模式 * 布局管理概述 * 文本输入 * 选择组件 * 菜单 * 复杂的布局管理 * 对话框 本章将介绍构造功能更加齐 ...
随机推荐
- Linux 粘着位(sticky bit)
当设置粘着位时只有root或者owner才能删除.重命名文件. 示例: 用户apple默认组为fruit. [root@titan ~]# id apple uid=1001(apple) gid=1 ...
- java中使用poi导出excel表格数据并且可以手动修改导出路径
在我们开发项目中,很多时候会提出这样的需求:将前端的某某数据以excel表格导出,今天就给大家写一个简单的模板. 这里我们选择使用poi导出excel: 第一步:导入需要的jar包到 lib 文件夹下
- 【性能测试工具】- ApacheBench
优点:提供的测试结果信息更完备:缺点:每次只能测试一个链接 概述: ab全称是ApacheBench,是 Apache 附带的一个HTTP性能测试小工具,可以同时模拟多个并发请求. 安装: Apach ...
- Java并发工具类 - CountDownLatch
Java并发工具类 - CountDownLatch 1.简介 CountDownLatch是Java1.5之后引入的Java并发工具类,放在java.util.concurrent包下面 http: ...
- 备注: ubt 16.04 安装 gtx 1060 --- 成功运行 tensorflow - gpu
---------------------------------------------------------------------------------------------------- ...
- nmake学习笔记2
makefile中的“@<<”看起来很奇怪,查很多地方都没有结果.写了两个示例比较其结果: 如果makefile如下: All:main.obj func.obj link $** .cp ...
- HTML5之dir属性
<p style="text-align:center"><bdo dir="RTL">芙蓉楼送辛渐</bdo></p ...
- ABP从入门到精通(5):使用基于JWT标准的Token访问WebApi
项目:asp.net zero 4.2.0 .net core(1.1) 版本 我们做项目的时候可能会遇到需要提供api给app调用,ABP动态生成的WebApi提供了方便的基于JWT标准的Token ...
- 安卓APP测试容易忽略的地方
我们手机APP测试,主要针对的是android和ios两大主流操作系统,总体上来说android手机型号.版本多,bug也多:ios相对bug少.下面就针对Android说一下最容易忽略的测试点吧. ...
- ExpandableListView实现手风琴效果
1. 效果示例图 2. 创建方法 (1)第一种方法与ListView等普通控件一样,直接在布局文件中添加ExpandableListView控件即可. (2)第二种方法则是创建一个Activity继承 ...