Java Swing组件文件选择器组件文件选择器JFileChooser简单用法示例简单用法示例
主要介绍了Java Swing组件文件选择器JFileChooser简单用法,结合实例形式分析了Swing组件中的文件选择器
JFileChooser的简单使用方法,需要的朋友可以参考下
本文实例讲述了Java Swing组件文件选择器JFileChooser简单用法。分享给大家供大家参考,具体如下:
先来看效果:
说明:选择文件或者文件夹。本例子就直接在控制台输出文件或者文件夹的路径。实际开发中,就可以将文件或文件夹的路径
封装为File的实例来使用了。
具体代码如下:
package awtDemo;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
@SuppressWarnings("serial")
public class FileChooser extends JFrame implements ActionListener{
JButton open=null;
public static void main(String[] args) {
new FileChooser();
}
public FileChooser(){
open=new JButton("open");
this.add(open);
this.setBounds(400, 200, 100, 100);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
open.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
jfc.showDialog(new JLabel(), "选择");
File file=jfc.getSelectedFile();
if(file.isDirectory()){
System.out.println("文件夹:"+file.getAbsolutePath());