首页 > 编程 > Java > 正文

Java Swing组件文件选择器JFileChooser简单用法示例

2019-11-26 10:57:13
字体:
来源:转载
供稿:网友

本文实例讲述了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());    }else if(file.isFile()){      System.out.println("文件:"+file.getAbsolutePath());    }    System.out.println(jfc.getSelectedFile().getName());  }}

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

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表