JavaFX学习之道:File Chooser

This chapter explains how to use the FileChooser class to enable users to navigate the file system. The samples provided in this chapter explain how to open one or several files, configure a file
chooser dialog window, and save the application content.

Unlike other user interface component classes, the FileChooser class does not belong to thejavafx.scene.controls package. However,
this class deserves to be mentioned in the JavaFX UI Controls tutorial, because it supports one of the typical GUI application functions: file system navigation.

The FileChooser class is located in the javafx.stage package along with the other basic root graphical elements, such as StageWindow,
and Popup. The View Pictures window in Figure
26-1
is an example of the file chooser dialog in Windows.

Figure 26-1 Example of a File Chooser Window

Description of "Figure 26-1 Example of a File Chooser Window"

Opening Files

A file chooser can be used to invoke an open dialog window for selecting either a single file or multiple files, and to enable a file save dialog window. To display a file chooser, you typically use the FileChooser class. Example
26-1
 provides the simplest way to enable a file chooser in your application.

Example 26-1 Showing a File Chooser

FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
fileChooser.showOpenDialog(stage);

After the code from Example 26-1 is added to a JavaFX application, the file chooser
dialog window appears immediately when the application starts, as shown in Figure 26-2.

Figure 26-2 Simple File Chooser

Description of "Figure 26-2 Simple File Chooser"


Note:

Figure 26-2 shows the file chooser in Windows. When you open
file choosers in other operating systems that support this functionality, you receive alternative windows. Figure
26-3
 and Figure 26-4 show examples of file chooser windows in Linux and Mac OS.

Figure 26-3 File Chooser Window in Linux

Description of "Figure 26-3 File Chooser Window in Linux"

Figure 26-4 File Chooser Window in Mac OS

Description of "Figure 26-4 File Chooser Window in Mac OS"

Although in the previous example the file chooser appears automatically when the application starts, a more typical approach is to invoke a file chooser by selecting the corresponding menu item or clicking a dedicated button. In
this tutorial, you create an application that enables a user to click a button and open a one or more pictures located in the file system. Example
26-2
shows the code of the FileChooserSample application that implements this task.

Example 26-2 Opening File Chooser for Single and Multiple Selection

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();

    @Override
    public 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>() {
                @Override
                public void handle(final ActionEvent e) {
                    File file = fileChooser.showOpenDialog(stage);
                    if (file != null) {
                        openFile(file);
                    }
                }
            });

        openMultipleButton.setOnAction(
            new EventHandler<ActionEvent>() {
                @Override
                public 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
                );
        }
    }
}

In Example 26-2, the Open a Picture button enables the user to open a file chooser
for a single selection, and the Open Pictures button enables the user to open a file chooser for multiple selections. The setOnAction methods for these buttons are almost identical. The only
difference is in the method that is used to invoke a FileChooser.

  • The showOpenDialog method shows a new file open dialog in which one file can be selected. The method returns the value that specifies the file chosen by the user or nullif
    no selection has been made.
  • The showOpenMultipleDialog method shows a new file open dialog in which multiple files can be selected. The method returns the value that specifies the list of files chosen by the user or null if
    no selection has been made. The returned list cannot be modified and throws UnsupportedOperationException on each modification attempt.

Both methods do not return results until the displayed open dialog window is dismissed (in other words, until a user commits or cancels the selection).

When you compile and run the FileChooserSample application, it produces the window shown in Figure
26-5
.

Figure 26-5 FileChooserSample with Two Buttons

Description of "Figure 26-5 FileChooserSample with Two Buttons"

When you click either of the buttons, the dialog window shown in Figure 26-6 appears.
The opened file chooser dialog window shows the location that is the default for your operating system.

Figure 26-6 Default File Chooser Window

Description of "Figure 26-6 Default File Chooser Window"

Users of the FileChooserSample application may navigate to a directory containing pictures and select a picture. After a file is selected, it is opened with the associated application. The example code implements this by using the open method
of the java.awt.Desktop class:desktop.open(file);.


Note:

Availability of the Desktop class is platform dependent. Refer to API
documentation
 for more information on the Desktop class. You can also use the isDesktopSupported() method
to check if it is supported in your system.

You can improve the user experience for this application by setting the file chooser directory to the specific directory that contains the pictures.

Configuring a File Chooser

You can configure the file chooser dialog window by setting the initialDirectory and titleproperties
of a FileChooser object. Example 26-3 shows
how to specify the initial directory and a suitable title to preview and open pictures.

Example 26-3 Setting the Initial Directory and Window Title

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();

    @Override
    public 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>() {
                @Override
                public void handle(final ActionEvent e) {
                    configureFileChooser(fileChooser);
                    File file = fileChooser.showOpenDialog(stage);
                    if (file != null) {
                        openFile(file);
                    }
                }
            });

        openMultipleButton.setOnAction(
            new EventHandler<ActionEvent>() {
                @Override
                public 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
                );
        }
    }
}

The configureFileChooser method sets the View Pictures title and the path to the user home directory with the My Pictures sub-directory. When you compile and run the
FileChooserSample and click one of the buttons, the file chooser shown in Figure 26-7 appears.

Figure 26-7 Opening a Pictures Library

Description of "Figure 26-7 Opening a Pictures Library"

You can also let the users specify the target directory by using the DirectoryChooser class. In the code fragment shown in Example
26-4
, the click of the browseButton invokes thedirectoryChooser.showDialog method.

Example 26-4 Use of the DirectoryChooser Class

final Button browseButton = new Button("...");
browseButton.setOnAction(
    new EventHandler<ActionEvent>() {
        @Override
        public void handle(final ActionEvent e) {
            final DirectoryChooser directoryChooser =
                new DirectoryChooser();
            final File selectedDirectory =
                    directoryChooser.showDialog(stage);
            if (selectedDirectory != null) {
                selectedDirectory.getAbsolutePath();
            }
        }
    }
);

After the selection is performed, you can assign the corresponding value to the file chooser as follows: fileChooser.setInitialDirectory(selectedDirectory); .

Setting Extension Filters

As the next configuration option, you can set the extension filter to determine which files to open in a file chooser, as shown in Example
26-5
.

Example 26-5 Setting an Image Type Filter

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();

    @Override
    public 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>() {
                @Override
                public void handle(final ActionEvent e) {
                    configureFileChooser(fileChooser);
                    File file = fileChooser.showOpenDialog(stage);
                    if (file != null) {
                        openFile(file);
                    }
                }
            });

        openMultipleButton.setOnAction(
            new EventHandler<ActionEvent>() {
                @Override
                public 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
            );
        }
    }
}

In Example 26-5, you set an extension filter by using FileChooser.ExtensionFilter to
define the following options for file selection: All images, JPG, and PNG.

When you compile, run the FileChooserSample code from Example 26-5, and click
one of the buttons, the extension filters appear in the file chooser window. If a user selects JPG, then the file chooser displays only pictures of the JPG type. Figure
26-8
 captures the moment of selection JPG images in the My Pictures directory.

Figure 26-8 Filtering JPG Files in File Chooser

Description of "Figure 26-8 Filtering JPG Files in File Chooser"

Saving Files

In addition to opening and filtering files, the FileChooser API provides a capability to let a user specify a file name (and its location in the file system) for a
file to be saved by the application. The showSaveDialog method of the FileChooser class opens a save dialog window. Like other
show dialog methods, the showSaveDialog method returns the file chosen by the user or null if no selection has been performed.

The code fragment shown in Example 26-6 is an addition to the Menu sample.
It implements one more item of the context menu that saves the displayed image in the file system.

Example 26-6 Saving an Image with the FileChooser Class

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());
                }
            }
        }
    }
);

When you add Example 26-6 to the MenuSample application (find the source code
in the Application Files), compile and run it, you enable the Save Image menu item, as shown inFigure 26-9.

Figure 26-9 Saving Image

Description of "Figure 26-9 Saving Image"

After a user selects the Save Image item, the Save Image window shown in Figure 26-10appears.

Figure 26-10 The Save Image Window

Description of "Figure 26-10 The Save Image Window"

The Save Image window corresponds to the typical user experience for the save dialog windows: the user needs to select the target directory, type in the name of the saving file, and click Save.

Related API Documentation

JavaFX学习之道:File Chooser

时间: 2024-10-08 17:45:06

JavaFX学习之道:File Chooser的相关文章

JavaFX学习之道:FileChooser 、POI导出Excel文件

以下是JavaFX中导出Excel的核心代码: private HSSFWorkbook workbook; /* Build Operation Button Area */ Button exportBn = ButtonBuilder.create().text("导出Excel").prefWidth(80).prefHeight(30).build(); exportBn.setDefaultButton(true); exportBn.setOnAction(new Eve

JavaFX学习之道:文本Text及其特效

原文地址http://download.oracle.com/javafx/2.0/text/jfxpub-text.htm 文本讲述如何在JavaFX2.0应用中加入文本和如何为文本提供花俏的效果. 引子 JavaFX 2.0应用的图形内容包含一些对象,它们被组织在一个成为场景图的类树结构中.场景图中的每个元素成为一个结点,结点可以管理很多不同种类的内容,包括文本.结点可以转换和移动,也可以应用多种效果.为所有结点类型使用共同特点使得可以提供复杂的文本内容来满足现在的富网络应用(RIAs).

JavaFX学习之道:JavaFX之TableView

TableView表 TableColumn列 构建一个表主要有TableView,TableColumn,ObservableList,Bean. 添加列table.getColumns().addAll(firstNameCol, lastNameCol, emailCol); ObservableList里面是存放的数据 table.setItems(observableList);添加数据 observableList里面一般是存放的Bean,列与Bean之间建立联系,从而获取值. 列与

JavaFx学习之道:JavaFx初步了解

因为项目的需要,实在是没有办法了,试了很多种方案(RCP,SWT,Flex,Smartinvoke...),最终还是决定开始研究JavaFx...为了给用户更好地体验我们的"智能家居"! 以下是最近搜索得到的一些资料: 1.Oracle 上 JavaFx的下载页面:http://www.oracle.com/technetwork/java/javafx/overview/index.html 目前最新版本的SDK是2.1 JavaFX 2.1 Developer Preview -

JavaFX学习之道:FXML入门

FXML是JavaFX 2.0提供的新技术.你可能会问"什么是FXML?","对我来说有什么用?". FXML是一种在JavaFX应用程序中定义用户界面的,基于XML的声明性标记语言.FXML非常适合用来静态布局,如表单.控件和表格.使用FXML,您还可以通过脚本动态地构建布局. FXML的优势之一是基于XML,是大多数开发人员所熟悉的,尤其是Web开发人员和使用其他RIA平台的开发人员.另一个优点是,FXML是不是编译语言,你不需要重新编译代码就可看到您所做的更改

JavaFX学习之道:JavaFX API详解之Window,Stage,PopupWindow

stage包中包含 Window, Stage, PopupWindow, Popup, FileChooser, DirectoryChooser, Screen等类. 其中Window类可理解成一个窗体,用于存放Scene,并与用户操作.一般window作为窗体,都用其子类Stage和PopupWindow. 看一下Window作为窗体的顶级类包含的一些共同属性 eventDispatcher setEventDispatcher(EventDispatcher value) focused

JavaFX学习之道:详解JavaFX架构与框架

JavaFX 2.0平台是基于Java技术的富客户端平台.它使应用程序开发者更加容易的开发和部署跨平台的富互联网应用(RIA).JavaFX 2.0文档包含了JavaFX 2.0所提供的功能的概述. 图1描述了JavaFX 2.0平台的架构组件.后面的部分将对每一个组件进行逐一的描述.在JavaFX通用API的下面是用来运行JavaFX代码的引擎.这个引擎包括以下子组件:JavaFX高性能图形引擎(Prism);新的更小但更有效率的窗体系统(Glass);媒体引擎和Web引擎.虽然这些组件不是包

JavaFX学习之道:文本框TextField

原文地址http://download.oracle.com/javafx/2.0/ui_controls/text-field.htm TextField类实现了一种可以接受和显示文本输入的UI控件,它提供了接受用户输入的功能.和另一个文本输入控件PasswordField一起都继承了TextInput这个类,TextInput是所有文本控件的父类. Figure 8-1 是一个带有标签的典型文本框. Figure 8-1 Label and Text Field Description of

JavaFX学习之道:使用JavaFX2.0的属性和绑定

目录(?)[+]                                     (原文:斯科特霍梅尔/甲骨文高级技术专家) 原文地址:http://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm 本教程通过一些可以编译和运行的例子描述了JavaFX的属性和绑定.关于JavaFX的安装,请参阅JavaFX安装指南. 概述 很多年以来,Java语言一直使用JavaBean来表示对象的属性,这种模式既包含API,也包含设计模式,它已经广