项目一:文件及选择
目的:了解文件对话框的使用方法,熟悉GUI中事件驱动的核心步骤。
1. 阅读博文 “
JFileChooser (Java Swing提供的文件选择对话框)”,了解博文大意。
2. 在IDE中输入(非复制、粘贴)博文中的代码,调试并运行。
3.
在上述界面中,增加如下控件:
JLabel,显示文本为“所选文件or文件夹:”;
JTextField,当选择了文件or文件夹后,显示所选择的文件or文件夹。
4. 完成上述功能。
package com.liang;
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;
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());
}
}
JFileChooser 效果图: