【Java學習】JFileChooser(檔案選擇器)的使用
一、概述。
javax.swing.JFileChooser()(檔案選擇器)提供了一種檔案選擇機制,一般用於開啟檔案,儲存檔案。
二、常用方法。
構造器:
1. public JFileChooser() : 構造一個JFileChooser物件,預設開啟的資料夾為使用者資料夾。
2. public JFileChooser(File currentDiretory) & public JFileChooser(String currentDiretory) : 建立一個開啟資料夾currentDiretory的JFileChooser物件。
3. public JFileChooser(FileSystemView fsv) : 建立一個基於fsv檔案系統外觀的JFileChooser物件。(引數說明:FileSystemView:檔案系統外觀,不設定則預設為當前檔案系統的外觀)
4. public JFileChooser(File currentDiretory, FileSystemView fsv) & public JFileChooser(String currentDiretory, FileSystemView fsv) : 建立一個開啟資料夾currentDiretory,基於fsv檔案系統外觀的JFileChooser物件。
【注】建立JFileChooser物件時無需指定parent元件,說明多個元件可以共用一個JFileChooser物件。
成員方法:
*各種引數設定
1.public void setCurrentDiretory(File dir) : 設定預設開啟的資料夾。
2.public void setSelectedFile(File file) / public void setSelectedFiles(File[ ] selectedFiles) : 設定開啟時預設選擇的檔案,可預設選擇多個。
3.public void setSelectionMode(int mode) : 設定選擇模式,預設情況為只可選檔案,也可設定為只選資料夾,或可選檔案及資料夾。(引數說明:可選引數為JFileChooser.FILES_ONLY / DIRETORY_ONLY / FILES_AND_DIRETORY)。
4.public void setMultiSelectionEnable(boolean b) : 預設只可選擇一個目標,該方法設定引數為true可允許多選。
5.public void addChoosableFileFilter(FileFilter filter) : 在原有過濾器的基礎上新增檔案過濾器filter。
6.public void setFileFilter(FileFilter filter) : 設定檔案過濾器filter,注意這將會清空之前的所有過濾器。
*呼叫選擇對話方塊
1.public int showDialog(Component parent, String approveButtonText) / showOpenDialog(Component parent) / showSaveDialog(Component parent) : 彈出檔案對話方塊,approveButtonText為“同意”按鈕的文字,檔案選擇器常用於開啟檔案和儲存檔案,故提供了後兩個方法,自動設定“同意”按鈕的文字為“開啟”和“儲存”。返回一個int值,分別是 JFileChooser.APPROVE_OPTION,JFileChooser.CANCEL_OPTION和JFileChooser.ERROR_OPTION。在獲取使用者選擇的檔案之前,通常先驗證返回值是否為APPROVE_OPTION.
*獲取使用者選擇的檔案
1.public File getSelectedFile() / pulbic File[ ] getSelectedFiles() : 返回使用者選擇的檔案或檔案集合。
三、使用說明。
事實上,用檔案選擇器來進行檔案及資料夾的選擇操作十分簡單,比如以下程式碼即能簡單的選擇檔案。
// 建立一個JFrame元件為parent元件
JFrame frame = new JFrame();
// 建立一個預設開啟使用者資料夾的問價選擇器
JFileChooser chooser = new JFileChooser();
int flag = chooser.showOpenDialog(frame);
//若選擇了檔案,則列印選擇了什麼檔案
if (flag == JFileChooser.APPROVE_OPTION)
System.out.println("使用者選擇了檔案:" + chooser.getSelectedFile().getName());
但是,在選擇的時候,我們經常需要設定哪些型別的檔案可見可選,比如,希望一個圖片瀏覽器只能開啟gif、jpg等圖片類的檔案,這時候就需要結合javax.swing.filechooser包下的抽象類FileFilter(檔案過濾器)來使用。下面介紹一下FileFilter類的簡單使用。
繼承FileFilter抽象類,需要重寫兩個抽象函式:
1.public abstract boolean accept(File file) : 判斷檔案是否可接受,只有可接受的檔案才會在檔案選擇器顯示。這是該抽象類的主要方法,實現了過濾功能。下面重寫該方法,使該檔案器只接受以mp4結尾的檔案。
public boolean accept(File file){
//資料夾必須是可選(開啟)的
if(file.isDirectory()) return true;
//以mp4結尾,設定為可選
else if(file.getName().endsWith(".mp4")) return true;
//其它的檔案型別都設定為不可選
return false;
2.public abstract void String getDescription() : 返回該檔案過濾器的描述性內容。
四、專案例項--圖片檢視器。
import javax.swing.*;
import javax.swing.filechooser.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
public class JFileChooserTest {
//設定預覽大小
final int PREVIEW_SIZE=100;
JFrame frame=new JFrame("圖片檢視器");
JMenuBar menuBar=new JMenuBar();
//該label用於顯示圖片
JLabel label=new JLabel();
//在當前路徑下建立檔案選擇器
JFileChooser chooser=new JFileChooser(".");
//該Label用於顯示預覽
JLabel accessory=new JLabel();
//定義檔案過濾器
ExtensionFileFilter filter=new ExtensionFileFilter();
FileInputStream fileInput;
FileOutputStream fileOutput;
public void init() {
//------------下面初始化JFileChooser的相關屬性--------------------
filter.addExtension("jpg");
filter.addExtension("jpeg");
filter.addExtension("gif");
filter.addExtension("png");
filter.setDescription("檔案圖片(*.jpg, *.jpeg, *.gif, *png)");
chooser.addChoosableFileFilter(filter);
//隱藏下拉列表中的“所有檔案”選項
chooser.setAcceptAllFileFilterUsed(false);
//為檔案選擇器指定一個預覽圖片的附件
chooser.setAccessory(accessory);
//設定預覽元件的大小和邊框
accessory.setPreferredSize(new Dimension(PREVIEW_SIZE,PREVIEW_SIZE));
accessory.setBorder(BorderFactory.createEtchedBorder());
//用於檢測被選檔案改變的事件
chooser.addPropertyChangeListener(event->{
if(event.getPropertyName()==JFileChooser.SELECTED_FILE_CHANGED_PROPERTY) {
//獲取使用者新選擇的檔案
File f=(File)event.getNewValue();
if(f==null) {
accessory.setIcon(null);
return;
}
//將被選檔案讀入ImageIcon物件中
ImageIcon icon=new ImageIcon(f.getPath());
//如果檔案太大,則縮小它
if(icon.getIconWidth()>PREVIEW_SIZE) {
icon=new ImageIcon(icon.getImage().getScaledInstance(
PREVIEW_SIZE, -1, Image.SCALE_DEFAULT));
}
//改變accessory的圖示
accessory.setIcon(icon);
}
});
//-----------下面開始為視窗安排選單--------------
JMenu menu=new JMenu("檔案");
menuBar.add(menu);
JMenuItem openItem=new JMenuItem("開啟");
JMenuItem copyItem=new JMenuItem("儲存副本為..");
copyItem.setEnabled(false);
menu.add(openItem);
menu.add(copyItem);
//單擊“開啟”彈出檔案選擇視窗
openItem.addActionListener(event->{
//顯示檔案對話方塊
int result=chooser.showOpenDialog(frame);
if(result==JFileChooser.APPROVE_OPTION) {
String name=chooser.getSelectedFile().getPath();
label.setIcon(new ImageIcon(name));
try {
fileInput=new FileInputStream(name);
copyItem.setEnabled(true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
//實現圖片的複製儲存
copyItem.addActionListener(event->{
int result=chooser.showSaveDialog(frame);
if(result==JFileChooser.APPROVE_OPTION) {
String name=chooser.getSelectedFile().getName();
File f=new File(name);
try {
fileOutput=new FileOutputStream(f);
byte[] bytes=new byte[1024];
int hasRead;
while((hasRead=fileInput.read(bytes,0, 1024))!=-1) {
fileOutput.write(bytes,0,hasRead);
}
fileOutput.close();
fileInput.close();
}catch(IOException ioe) {
ioe.printStackTrace();
}
}
});
JMenuItem exitItem=new JMenuItem("Exit");
menu.add(exitItem);
exitItem.addActionListener(event->System.exit(0));
label.setPreferredSize(new Dimension(500,500));
frame.setJMenuBar(menuBar);
frame.add(new JScrollPane(label));
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new JFileChooserTest().init();
}
//建立FileFilter的子類,用於實現檔案過濾功能
class ExtensionFileFilter extends FileFilter{
private String description;
private ArrayList<String> extensions=new ArrayList<>();
//自定義方法,用於新增檔案字尾名
public void addExtension(String extension) {
if(!extension.startsWith("."))
extension="."+extension;
extensions.add(extension.toLowerCase());
}
//用於設定該檔案過濾器的描述文字
public void setDescription(String description) {
this.description=description;
}
public String getDescription() {
return description;
}
public boolean accept(File file) {
if(file.isDirectory()) return true;
String name=file.getName().toLowerCase();
for(String extension:extensions) {
if(name.endsWith(extension)) return true;
}
return false;
}
}
}
五、更多詳細內容請參看API:https://docs.oacle.com/javase/8/docs/api/javax/swing/JFileChooser.html