JavaFX UI控件教程(二十七)之File Chooser

翻译自  File Chooser

本章介绍如何使用FileChooser该类使用户能够导航文件系统。本章提供的示例说明了如何打开一个或多个文件,配置文件选择器对话框窗口以及保存应用程序内容。

与其他用户界面组件类不同,FileChooser该类不属于该javafx.scene.controls包。但是,这个类值得在JavaFX UI Controls教程中提及,因为它支持典型的GUI应用程序功能之一:文件系统导航。

FileChooser类位于javafx.stage包与其他的基本根图形元素,例如沿着StageWindow,和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中的“文件选择器”窗口

Description of Figure 26-4 follows

虽然在前面的示例中,文件选择器在应用程序启动时自动出现,但更典型的方法是通过选择相应的菜单项或单击专用按钮来调用文件选择器。在本教程中,您将创建一个应用程序,使用户可以单击按钮并打开位于文件系统中的一个或多个图片。例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()方法检查系统是否支持它。

通过将文件选择器目录设置为包含图片的特定目录,可以改善此应用程序的用户体验。

 

配置文件选择器

您可以通过设置对象的属性initialDirectorytitle属性来配置文件选择器对话框窗口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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/324997.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

sql server高级查询,看这篇文章就够了

先选择一个数据库 use jobtest go引入&#xff1a;该数据库jobtest里面有两张表&#xff0c;Student学生表和Grade年级表&#xff0c;表中的数据如下所示&#xff1a; 学生表Student&#xff1a; 年级Grade表&#xff1a; 接下来我们来看看sql server中的子查询&#xff1a…

ssl1104-USACO 2.1城堡(foodfill)【图论,广搜】

##前言 由于这道题比较难&#xff0c;有不好描述&#xff0c;我就直接贴题目了。 ##Description 以一个几乎超乎想像的运气&#xff0c;农民约翰在他的生日收到了一张爱尔兰博彩的奖券。 这一张奖券成为了唯一中奖的奖券。 农民约翰嬴得爱尔兰的乡下地方的一个传说中的城堡。 …

直接输出数组的名字不一定是地址值

package com.wdl.day09;/*** 创建人 wdl* 创建时间 2021/8/12* 描述*/ public class ArrayPrintTest {public static void main(String[] args) {int[] arr new int[]{1, 2, 3};System.out.println(arr);//地址值char[] arr1 {a, b,c};System.out.println(arr1);//abc} }

jQuery的简介

jQuery的简介 [1]为什么学习jQuery A、JS书写代码的时候结构比较的臃肿 B、JS获得元素对象的方式比较的单一 C、JS书写的代码浏览器的兼容性比较差 D、JS实现动画的效果比较的麻烦 [2]什么是jQuery javascriptQuery(js库) 目前最流行的JavaScript函数库&#xff0c;对JavaScrip…

JavaFX UI控件教程(二十八)之UI控件的自定义

翻译自 Customization of UI Controls 本章介绍了UI控件自定义的各个方面&#xff0c;并总结了Oracle提供的一些提示和技巧&#xff0c;以帮助您修改UI控件的外观和行为。 您可以通过应用层叠样式表&#xff08;CSS&#xff09;&#xff0c;重新定义默认行为和使用单元工厂来…

好多人都说存储过程很难?认真看这篇文章就够了

何为存储过程&#xff1f;存储过程是在数据库管理系统中保存的、预先编译的并能实现某种功能的sql程序&#xff0c;说直白点&#xff0c;java知道吧&#xff1f;和java的方法一样。每遇到一个新的知识点时&#xff0c;我们都会看看它的优点&#xff0c;从而加深对它学习的欲望&…

下一代的 Actor 模型框架 Proto Actor

ProtoAct 是下一代的 Actor 模型框架&#xff0c;提供了 .NET 和 Go 语言的实现&#xff0c;默认支持分布式&#xff0c;提供管理和监控功能。在过去几年&#xff0c;我们经常看到两种 Actor 模型方法相互竞争&#xff0c;首先是经典的 Erlang/Akka 风格的 Actor 模型&#xff…

ssl1776-游乐场【图论,深搜】

题目 一个游乐场&#xff08;无向图&#xff09;&#xff0c;每个景点&#xff08;点&#xff09;都有一定的开心值&#xff08;价值&#xff09;&#xff0c;一个点只能游玩一次。然后可以从任何一个点出发&#xff0c;求可以游玩的最多项目&#xff08;连通分量&#xff09;…

JQuery $作用

作用1&#xff1a; $(function&#xff08;&#xff09;{}) $就是jQuery的省略写法 1.相当于 window.οnlοadfunction(){} 2.功能比window.onload更强大 1) window onload一个页面只能写一个,但是可以写多个$() 而不冲突 2) window onload要等整个页面加载完后再执行&#xff…

import关键字

在源文件中显式的使用import结构导入指定包下的类、接口 声明在包的声明和类的声明之间 如果需要导入多个结构&#xff0c;则并列写出即可 可以使用"xxx.*"的方式&#xff0c;表示可以导入xxx包下的所有结构 如果使用的类或接口是java.lang包下定义的&#xff0c…

信息学奥赛一本通1349-最优布线问题

【题目描述】 学校有n台计算机&#xff0c;为了方便数据传输&#xff0c;现要将它们用数据线连接起来。两台计算机被连接是指它们有数据线连接。由于计算机所处的位置不同&#xff0c;因此不同的两台计算机的连接费用往往是不同的。 当然&#xff0c;如果将任意两台计算机都用…

你知道i=i++;的含义吗?原理其实没有你想的那么简单

i和i我们都知道&#xff0c;但是你知道ii;吗&#xff1f;自上学时&#xff0c;老师就说i是先赋值再加&#xff0c;而i是先加再赋值&#xff0c;比如我们写个代码举下例子&#xff1a;i:/*** 自增案例*/public static void testZiZeng(){int i 1;int a i;System.out.println(&…

jQuery 的选择器

01、基本选择器 标签选择器 $(“a”) ID选择器 $(“#id”) $(“p#id”) 类选择器 $(“.class”) $(“h2.class”) 通配选择器 $("*") 并集选择器$(“elem1,elem2,elem3”) <script type"text/javascript">$(function(){/*******id选择器*********…

学会思考,而不只是编程

中国人常说“授之以鱼不如授之以渔”。如果说教授编程是授之以鱼&#xff0c;那么教授计算机科学就是授之以渔。为什么说学习计算机科学比学会编程要重要得多&#xff1f;来听听Yevgeniy Brikman的解释。 现如今&#xff0c;似乎每个人都在学习编程&#xff1a;Bill Gates、Ma…

ssl1562-局域网

局域网 题目 就是一个图&#xff0c;求最小生成树&#xff0c;然后求被去除的边的价值。 输入 用线来表示联通 5 5 1 2 8 1 3 1 1 5 3 2 4 5 3 4 2 输出 去除的边的总价值 8 解题思路 求出最小生成树的价值然后线的总值减去最小生成树的价值 代码 #include<…

什么?java中居然可以执行js代码了?真是不知者不怪

今天在书上看的&#xff0c;java中可以直接调用js的函数了&#xff0c;言外之意就是java已经支持外部的脚本语言了&#xff08;在运行期解释执行的&#xff09;&#xff0c;查了查&#xff0c;jdk从1.6之后开始支持的&#xff0c;1.6之前不可以。 为什么Java这种编译语言还需要…

jQuery 操作元素

01、操作元素的属性 $(function(){$("#but").click(function(){//获得元素的对象var inp$("#zh");//JQ获得属性 inp.attr("value")&#xff1a;获得的默认的值console.log(inp.attr("type")"----"inp.attr("name&q…

用 Docker Machine 创建 Azure 虚拟主机

搭建环境向来是一个重复造轮子的过程&#xff0c;Docker Machine 则把用户搭建 Docker 环境的各种方案汇集在了一起。笔者在《Docker Machine 简介》一文中演示了使用 Docker Machine 在本地的 vSphere 主机中安装 Docker 环境。但是在云计算大爆炸的今天&#xff0c;真正让我们…

ssl2345-繁忙的都市

题目 一个无向图&#xff0c;求最小生成树里权值最大的那条边 输入 第一行有两个整数n,m表示有n个店&#xff0c;m条边。接下来m行是对每条边的描述&#xff0c;u, v, c表示点u和v之间有边&#xff0c;权值为c。(1≤n≤300&#xff0c;1≤c≤10000) 4 5 1 2 3 1 4 5 2 4…

JQuery 事件绑定

<script type"text/javascript">$(function(){/******单击事件的绑定********/$("#bu1").click(function(){alert("单击事件");})$("#bu1").dblclick(function(){})$("#bu1").blur(function(){ })/******绑定多个事件…