1.文件选择对话框的用户创建经常使用打开和保存文件的对话框,它是一个独立的组件,我们可以使用文件选择器打开文件和保存文件,有时候将图片和文件保存到数据库,可以使用文件选择器获取文件路径,并把文件路径保存到数据库即可。
2.文件选择器代码实例
package com.Swing;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class FileChooserDemo extends JFrame implements ActionListener{
private JTextArea ta;
private JFileChooser jfc=new JFileChooser(new File("."));
private JButton bOpen,bSave;
private JScrollPane ps;
public FileChooserDemo(){
ta=new JTextArea(10,20);
ps=new JScrollPane(ta);
bOpen=new JButton("选择文件");
bSave=new JButton("保存文件");
bOpen.addActionListener(this);
bSave.addActionListener(this);
this.add(ps);
this.add(bOpen);
this.add(bSave);
this.setTitle("文件选择器的使用");
this.setLayout(new FlowLayout(FlowLayout.CENTER,15,10));
this.setSize(300,300);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
JButton jbt= (JButton) e.getSource();
//1.点击bOpen要做的事为
if(jbt==bOpen){
//打开文件选择器对话框