JFileChooser()
構造一個指向用戶默認目錄的 JFileChooser。
JFileChooser(File currentDirectory)
使用給定的 File
作為路徑來構造一個 JFileChooser
。
setFileSelectionMode(int mode)
設置 JFileChooser
,以允許用戶只選擇文件、只選擇目錄,或者可選擇文件和目錄。
mode參數:FILES_AND_DIRECTORIES
指示顯示文件和目錄。
FILES_ONLY
指示僅顯示文件。
DIRECTORIES_ONLY
指示僅顯示目錄。
showDialog(Component parent,String approveButtonText)
彈出具有自定義 approve 按鈕的自定義文件選擇器對話框。
showOpenDialog(Component parent)
彈出一個 "Open File" 文件選擇器對話框。
showSaveDialog(Component parent)
彈出一個 "Save File" 文件選擇器對話框。
setMultiSelectionEnabled(boolean b)
設置文件選擇器,以允許選擇多個文件。
getSelectedFiles()
如果將文件選擇器設置為允許選擇多個文件,則返回選中文件的列表(File[])。
getSelectedFile()
返回選中的文件。
button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //按鈕點擊事件 JFileChooser chooser = new JFileChooser(); //設置選擇器 chooser.setMultiSelectionEnabled(true); //設為多選 int returnVal = chooser.showOpenDialog(button); //是否打開文件選擇框 System.out.println("returnVal="+returnVal); if (returnVal == JFileChooser.APPROVE_OPTION) { //如果符合文件類型 String filepath = chooser.getSelectedFile().getAbsolutePath(); //獲取絕對路徑 System.out.println(filepath); System.out.println("You chose to open this file: "+ chooser.getSelectedFile().getName()); //輸出相對路徑 } } });