JavaFX,Unity3D,Android,IOS等技术教程和生活随笔,仅供记录

http://www.wingmei.cn/wp-content/themes/Vtrois-Kratos-e85a527/images/background.jpg

从零开始学习JavaFX(18) 控件篇之File Chooser

这一章我们来看看FileChooser的使用。

其实从严格意义上来讲FileChooser并不属于控件,也不在javafx.scene.controls包名中,而是属于javafx.stage下。

可能大家会觉得FileChooser是继承与Stage的一个Stage窗口,但其实仔细看源码就会发现,FileChooser只是一个普通的类而已,主要是通过Toolkit.getToolkit().showFileChooser来显示对话框,Toolkit是com.sun.javafx.tk.Toolkit工具类。

而在Toolkit中,showFileChooser最终的追踪是到com.sun.glass.ui包,通过Application.GetApplication().staticCommonDialogs_showFileChooser来创建文件选择框,当然,到这里就跟JavaFX没什么关系了。

下面我们来看看FileChoose的用法:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        AnchorPane root = new AnchorPane();

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("打开文件");

        Button btn = new Button("打开文件");
        btn.setOnAction(event -> {
            fileChooser.showOpenDialog(primaryStage);
        });

        root.getChildren().add(btn);
        primaryStage.setTitle("文件选择FileChooser");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

大家可以看到,很简单的new了一个FileChooser并设置了标题,然后通过showOpenDialog来显示。

运行效果如下:

《从零开始学习JavaFX(18) 控件篇之File Chooser》

下面我们来获取选择的文件,并将路径显示出来,修改代码如下:

      Label mLabel = new Label();
        mLabel.setLayoutY(40);

        Button btn = new Button("打开文件");
        btn.setOnAction(event -> {
            File file = fileChooser.showOpenDialog(primaryStage);
            if(file != null){
                mLabel.setText(file.getAbsolutePath());
            }else {
                mLabel.setText("没有打开任何文件");
            }
        });

        root.getChildren().addAll(btn,mLabel);

获取到选择的文件,然后将路径显示在Label上。

《从零开始学习JavaFX(18) 控件篇之File Chooser》

如果要选择多个文件,那么使用fileChooser.showOpenMultipleDialog来获取文件列表,并做相应的操作吧。

另外,我们可以使用fileChooser.setInitialDirectory来设置起始目录,例如:

fileChooser.setInitialDirectory(
            new File(System.getProperty("user.dir"))
        ); 

当然,还有一个文件选择更常用的功能,就是文件过滤了,可以选择显示指定格式的文件:

fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("All Images", "*.*"),
                new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                new FileChooser.ExtensionFilter("PNG", "*.png")
            );

运行效果如下:

《从零开始学习JavaFX(18) 控件篇之File Chooser》

这样就能过滤指定格式的文件了。

上述的都是打开文件对话框,至于保存文件对话框,则使用fileChooser.showSaveDialog,用法是一样的。

另外,如果我们需要选择文件夹的话,需要使用DirectoryChooser,使用与FileChooser类似,这里就不做过多的讲解了。

那么,这一章就到此结束了。

点赞

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注