JavaFX UI控件教程(二十七)之File Chooser
翻譯自??File Chooser
本章介紹如何使用FileChooser該類使用戶能夠導航文件系統。本章提供的示例說明了如何打開一個或多個文件,配置文件選擇器對話框窗口以及保存應用程序內容。
與其他用戶界面組件類不同,FileChooser該類不屬于該javafx.scene.controls包。但是,這個類值得在JavaFX UI Controls教程中提及,因為它支持典型的GUI應用程序功能之一:文件系統導航。
的FileChooser類位于javafx.stage包與其他的基本根圖形元素,例如沿著Stage,Window,和Popup。圖26-1中的“查看圖片”窗口是Windows中文件選擇器對話框的示例。
圖26-1文件選擇器窗口示例
?
打開文件
文件選擇器可用于調用打開的對話框窗口,用于選擇單個文件或多個文件,以及啟用文件保存對話框窗口。要顯示文件選擇器,通常使用FileChooser該類。例26-1提供了在應用程序中啟用文件選擇器的最簡單方法。
示例26-1顯示文件選擇器
FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open Resource File"); fileChooser.showOpenDialog(stage);將示例26-1中的代碼添加到JavaFX應用程序后,應用程序啟動時會立即顯示文件選擇器對話框窗口,如圖26-2所示。
圖26-2簡單文件選擇器
| 注意: 圖26-2顯示了Windows中的文件選擇器。在其他支持此功能的操作系統中打開文件選擇器時,您將收到備用窗口。圖26-3和圖26-4顯示了Linux和Mac OS中文件選擇器窗口的示例。 |
圖26-3 Linux中的文件選擇器窗口
圖26-4 Mac OS中的“文件選擇器”窗口
雖然在前面的示例中,文件選擇器在應用程序啟動時自動出現,但更典型的方法是通過選擇相應的菜單項或單擊專用按鈕來調用文件選擇器。在本教程中,您將創建一個應用程序,使用戶可以單擊按鈕并打開位于文件系統中的一個或多個圖片。例26-2顯示了實現此任務的FileChooserSample應用程序的代碼。
示例26-2打開單個和多個選擇的文件選擇器
import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage;public final class FileChooserSample extends Application {private Desktop desktop = Desktop.getDesktop();@Overridepublic void start(final Stage stage) {stage.setTitle("File Chooser Sample");final FileChooser fileChooser = new FileChooser();final Button openButton = new Button("Open a Picture...");final Button openMultipleButton = new Button("Open Pictures...");openButton.setOnAction(new EventHandler<ActionEvent>() {@Overridepublic void handle(final ActionEvent e) {File file = fileChooser.showOpenDialog(stage);if (file != null) {openFile(file);}}});openMultipleButton.setOnAction(new EventHandler<ActionEvent>() {@Overridepublic void handle(final ActionEvent e) {List<File> list =fileChooser.showOpenMultipleDialog(stage);if (list != null) {for (File file : list) {openFile(file);}}}});final GridPane inputGridPane = new GridPane();GridPane.setConstraints(openButton, 0, 0);GridPane.setConstraints(openMultipleButton, 1, 0);inputGridPane.setHgap(6);inputGridPane.setVgap(6);inputGridPane.getChildren().addAll(openButton, openMultipleButton);final Pane rootGroup = new VBox(12);rootGroup.getChildren().addAll(inputGridPane);rootGroup.setPadding(new Insets(12, 12, 12, 12));stage.setScene(new Scene(rootGroup));stage.show();}public static void main(String[] args) {Application.launch(args);}private void openFile(File file) {try {desktop.open(file);} catch (IOException ex) {Logger.getLogger(FileChooserSample.class.getName()).log(Level.SEVERE, null, ex);}} }在示例26-2中,“打開圖片”按鈕使用戶可以打開文件選擇器進行單個選擇,“打開圖片”按鈕使用戶可以打開文件選擇器進行多項選擇。setOnAction這些按鈕的方法幾乎相同。唯一的區別在于用于調用a的方法FileChooser。
-
該showOpenDialog方法顯示一個新的文件打開對話框,其中可以選擇一個文件。該方法返回指定用戶選擇的文件的值,或者null是否未進行選擇。
-
該showOpenMultipleDialog方法顯示了一個新的文件打開對話框,其中可以選擇多個文件。該方法返回指定用戶選擇的文件列表的值,或者null是否未進行選擇。無法修改返回的列表,并UnsupportedOperationException在每次修改嘗試時拋出。
兩種方法都不會返回結果,直到顯示的打開對話框窗口被取消(換句話說,直到用戶提交或取消選擇)。
編譯并運行FileChooserSample應用程序時,它會生成如圖26-5所示的窗口。
圖26-5帶有兩個按鈕的FileChooserSample
單擊其中一個按鈕時,將出現如圖26-6所示的對話框窗口。打開的文件選擇器對話框窗口顯示操作系統的默認位置。
圖26-6默認文件選擇器窗口
FileChooserSample應用程序的用戶可以導航到包含圖片的目錄并選擇圖片。選擇文件后,將使用關聯的應用程序打開該文件。示例代碼通過使用實現此open的方法java.awt.Desktop類:desktop.open(file);。
| 注意: Desktop該類的可用性取決于平臺。有關該類的更多信息,請參閱API文檔Desktop。您還可以使用該isDesktopSupported()方法檢查系統是否支持它。 |
通過將文件選擇器目錄設置為包含圖片的特定目錄,可以改善此應用程序的用戶體驗。
?
配置文件選擇器
您可以通過設置對象的屬性initialDirectory和title屬性來配置文件選擇器對話框窗口FileChooser。例26-3顯示了如何指定初始目錄以及預覽和打開圖片的合適標題。
示例26-3設置初始目錄和窗口標題
import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage;public final class FileChooserSample extends Application {private Desktop desktop = Desktop.getDesktop();@Overridepublic void start(final Stage stage) {stage.setTitle("File Chooser Sample");final FileChooser fileChooser = new FileChooser();final Button openButton = new Button("Open a Picture...");final Button openMultipleButton = new Button("Open Pictures...");openButton.setOnAction(new EventHandler<ActionEvent>() {@Overridepublic void handle(final ActionEvent e) {configureFileChooser(fileChooser);File file = fileChooser.showOpenDialog(stage);if (file != null) {openFile(file);}}});openMultipleButton.setOnAction(new EventHandler<ActionEvent>() {@Overridepublic void handle(final ActionEvent e) {configureFileChooser(fileChooser);List<File> list = fileChooser.showOpenMultipleDialog(stage);if (list != null) {for (File file : list) {openFile(file);}}}});final GridPane inputGridPane = new GridPane();GridPane.setConstraints(openButton, 0, 0);GridPane.setConstraints(openMultipleButton, 1, 0);inputGridPane.setHgap(6);inputGridPane.setVgap(6);inputGridPane.getChildren().addAll(openButton, openMultipleButton);final Pane rootGroup = new VBox(12);rootGroup.getChildren().addAll(inputGridPane);rootGroup.setPadding(new Insets(12, 12, 12, 12));stage.setScene(new Scene(rootGroup));stage.show();}public static void main(String[] args) {Application.launch(args);}private static void configureFileChooser(final FileChooser fileChooser){ fileChooser.setTitle("View Pictures");fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); }private void openFile(File file) {try {desktop.open(file);} catch (IOException ex) {Logger.getLogger(FileChooserSample.class.getName()).log(Level.SEVERE, null, ex);}} }該configureFileChooser方法使用“我的圖片”子目錄設置“查看圖片”標題和用戶主目錄的路徑。編譯并運行FileChooserSample并單擊其中一個按鈕時,將出現如圖26-7所示的文件選擇器。
圖26-7打開圖片庫
您還可以讓用戶使用DirectoryChooser該類指定目標目錄。在例26-4中顯示的代碼片段中,單擊它會browseButton調用該directoryChooser.showDialog方法。
示例26-4使用DirectoryChooser類
final Button browseButton = new Button("..."); browseButton.setOnAction(new EventHandler<ActionEvent>() {@Overridepublic void handle(final ActionEvent e) {final DirectoryChooser directoryChooser =new DirectoryChooser();final File selectedDirectory =directoryChooser.showDialog(stage);if (selectedDirectory != null) {selectedDirectory.getAbsolutePath();}}} );執行選擇后,您可以按如下方式將相應的值分配給文件選擇器:fileChooser.setInitialDirectory(selectedDirectory);。
?
設置擴展過濾器
作為下一個配置選項,您可以設置擴展過濾器以確定在文件選擇器中打開哪些文件,如例26-5所示。
示例26-5設置圖像類型過濾器
import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage;public final class FileChooserSample extends Application {private Desktop desktop = Desktop.getDesktop();@Overridepublic void start(final Stage stage) {stage.setTitle("File Chooser Sample");final FileChooser fileChooser = new FileChooser();final Button openButton = new Button("Open a Picture...");final Button openMultipleButton = new Button("Open Pictures..."); openButton.setOnAction(new EventHandler<ActionEvent>() {@Overridepublic void handle(final ActionEvent e) {configureFileChooser(fileChooser);File file = fileChooser.showOpenDialog(stage);if (file != null) {openFile(file);}}});openMultipleButton.setOnAction(new EventHandler<ActionEvent>() {@Overridepublic void handle(final ActionEvent e) {configureFileChooser(fileChooser); List<File> list = fileChooser.showOpenMultipleDialog(stage);if (list != null) {for (File file : list) {openFile(file);}}}});final GridPane inputGridPane = new GridPane();GridPane.setConstraints(openButton, 0, 1);GridPane.setConstraints(openMultipleButton, 1, 1);inputGridPane.setHgap(6);inputGridPane.setVgap(6);inputGridPane.getChildren().addAll(openButton, openMultipleButton);final Pane rootGroup = new VBox(12);rootGroup.getChildren().addAll(inputGridPane);rootGroup.setPadding(new Insets(12, 12, 12, 12));stage.setScene(new Scene(rootGroup));stage.show();}public static void main(String[] args) {Application.launch(args);}private static void configureFileChooser(final FileChooser fileChooser) { fileChooser.setTitle("View Pictures");fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("All Images", "*.*"),new FileChooser.ExtensionFilter("JPG", "*.jpg"),new FileChooser.ExtensionFilter("PNG", "*.png"));}private void openFile(File file) {try {desktop.open(file);} catch (IOException ex) {Logger.getLogger(FileChooserSample.class.getName()).log(Level.SEVERE, null, ex);}} }在示例26-5中,您可以使用FileChooser.ExtensionFilter以定義文件選擇的以下選項來設置擴展過濾器:所有圖像,JPG和PNG。
編譯時,運行例26-5中的FileChooserSample代碼,然后單擊其中一個按鈕,擴展名篩選器將出現在文件選擇器窗口中。如果用戶選擇JPG,則文件選擇器僅顯示JPG類型的圖片。圖26-8捕獲了My Pictures目錄中選擇JPG圖像的時刻。
圖26-8在文件選擇器中過濾JPG文件
?
保存文件
除了打開和過濾文件之外,FileChooserAPI還提供了一種功能,允許用戶為應用程序保存的文件指定文件名(及其在文件系統中的位置)。該類的showSaveDialog方法FileChooser打開一個保存對話框窗口。與其他show dialog方法一樣,該showSaveDialog方法返回用戶選擇的文件,或者null如果沒有執行選擇。
例26-6中顯示的代碼片段是Menu示例的補充。它還實現了上下文菜單中的另一項,用于將顯示的圖像保存在文件系統中。
示例26-6使用FileChooser類保存圖像
MenuItem cmItem2 = new MenuItem("Save Image");cmItem2.setOnAction(new EventHandler<ActionEvent>() {public void handle(ActionEvent e) {FileChooser fileChooser = new FileChooser();fileChooser.setTitle("Save Image");System.out.println(pic.getId());File file = fileChooser.showSaveDialog(stage);if (file != null) {try {ImageIO.write(SwingFXUtils.fromFXImage(pic.getImage(),null), "png", file);} catch (IOException ex) {System.out.println(ex.getMessage());}}}} );將Example 26-6添加到MenuSample應用程序(在Application Files中查找源代碼),編譯并運行它時,啟用Save Image菜單項,如圖26-9所示。
圖26-9保存圖像
用戶選擇“保存圖像”項后,將出現如圖26-10所示的“保存圖像”窗口。
圖26-10“保存圖像”窗口
“保存圖像”窗口對應于保存對話框窗口的典型用戶體驗:用戶需要選擇目標目錄,鍵入保存文件的名稱,然后單擊“保存”。
?
相關的API文檔?
-
FileChooser
-
DirectoryChooser
總結
以上是生活随笔為你收集整理的JavaFX UI控件教程(二十七)之File Chooser的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Unity:53% 开发者认为去年“恶意
- 下一篇: 《心灵杀手 2》总监谈游戏场景设计灵感: