javaFX学习之文件选择框FileChooser 您所在的位置:网站首页 强化廉洁自律意识筑牢廉洁自律防线 javaFX学习之文件选择框FileChooser

javaFX学习之文件选择框FileChooser

2024-07-15 00:04| 来源: 网络整理| 查看: 265

FileChooser类来让用户浏览文件系统。

样例程序解释了如何打开一个或多个文件,配置一个文件选择对话框并且保存应用程序内容

与其它UI控件类不同,FileChooser类并不属于javafx.scene.controls包。然而这个类值得在JavaFX UI控件教程中被提到,因为它支持一个经典的GUI应用程序功能:文件系统浏览

FileChooser类在javafx.stage包中,它与其它基本根图形元素在一起,例如Stage、Windows和Popup

打开文件

一个文件选择器可以用于调用一个“打开”对话框窗体来选择一个或多个文件,并且可以启用文件保存对话框窗体。为了展示一个文件选择框,一般可以使用FileChooser类

展现一个FileChooser

FileChooser fileChooser = new FileChooser();

fileChooser.setTitle("Open Resource File");

fileChooser.showOpenDialog(stage);

Windows操作系统中的文件选择器。当你在其它支持这个功能的操作系统中打开文件选择器时,你将会看到不同的窗体 

尽管在前面的样例中文件选择器都会在应用程序启动时自动出现,但是一个更为典型的应用方式是在选择了对应的菜单项或点击了特定的按钮时调用文件选择框 

import java.awt.*; 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.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 FileChooserTest extends Application { private final Desktop desktop = Desktop.getDesktop();//创建并获取windows操作系统桌面运行环境对象 @Override public void start(final Stage stage) { stage.setTitle("文件选择器样例"); final FileChooser fileChooser = new FileChooser();//文件选择器 final Button openButton = new Button("打开一个文件"); final Button openMultipleButton = new Button("打开多个文件"); openButton.setOnAction(//按钮对象交互事件处理机制 (final ActionEvent e) -> {//按钮事件处理回到函数 File file = fileChooser.showOpenDialog(stage);//在当前舞台环境下打开文件选择器 if (file != null) {//如果文件对象不为空则打开文件 openFile(file);//打开单个文件 } }); openMultipleButton.setOnAction(//按钮对象交互事件处理机制 (final ActionEvent e) -> {//按钮事件交互处理机制 List list = fileChooser.showOpenMultipleDialog(stage);//文件选择器打开多文件选择框,选中文件后将会返回一个文件列表对象 if (list != null) {//如果文件列表不是空的 list.stream().forEach((file) -> {//利用lamuda表达式循环迭代逐个打开文件 openFile(file);//打开文件的方法 }); } }); final GridPane inputGridPane = new GridPane();//格子布局面板对象 GridPane.setConstraints(openButton, 0, 0);//第一个打开按钮约定放在第一行第一列 GridPane.setConstraints(openMultipleButton, 1, 0);//第二个打开多文件按钮约定放在第一行第二列 inputGridPane.setHgap(6);//设置布局表格的水平间距为6 inputGridPane.setVgap(6);//设置布局表格的垂直间距为6 inputGridPane.getChildren().addAll(openButton, openMultipleButton);//布局面板对象上面添加此两个按钮 final Pane rootGroup = new VBox(12);//创建一个垂直盒子布局器 rootGroup.getChildren().addAll(inputGridPane);//垂直盒子布局器上添加表格布局器对象 rootGroup.setPadding(new Insets(12, 12, 12, 12));//设置垂直盒子布局器的内边距,利用Insets类型填充物对象来作为内边距的填充 stage.setScene(new Scene(rootGroup)); stage.show(); } public static void main(String[] args) { Application.launch(args); } private void openFile(File file) {//自定义的打开文件的方法 EventQueue.invokeLater(() -> {//操作系统事件队列响应调用回调方法 try { desktop.open(file);//桌面运行环境下下打开文件 } catch (IOException ex) { Logger.getLogger(FileChooserTest. class.getName()). log(Level.SEVERE, null, ex);//记录操作系统级别的异常信息 } }); } }

 

当一个文件被选择后,它将会使用关联应用程序来打开。样例代码通过使用java.awt.Desktop类的Open方法来实现此功能:desktop.open(file);。

注意:Desktop类的可用性是独立于平台的。参考Desktop类的API文档来了解更多的相关信息。你也可以使用isDesktopSupported()方法来检查你的操作系统是否支持它。

配置一个FileChooser

可以通过设置FileChooser对象的initialDirectory和title属性来配置文件选择对话框窗体来指定初始化目录和一个合适的标题来预览并打开相关目录

例子:设置初始化目录和窗体标题

import javafx.application.Application; import javafx.event.ActionEvent; 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; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.List; public final class FileChooserTest2 extends Application { private final Desktop desktop = Desktop.getDesktop();//获取并创建当前操作系统桌面应用环境对象 @Override public void start(final Stage stage) { stage.setTitle("文件选择器示例"); final FileChooser fileChooser = new FileChooser();//创建一个文件选择器对象 final Button openButton = new Button("打开一个文件_按钮"); final Button openMultipleButton = new Button("打开多个文件_按钮"); openButton.setOnAction(//打开文件按钮事件处理机制 (final ActionEvent e) -> { configureFileChooser(fileChooser);//自定义方法配置文件选择器对象 File file = fileChooser.showOpenDialog(stage);//在当前舞台对象环境下打开文件选择器对话框 if (file != null) {//如果文件路径不为空则打开文件 openFile(file);//自定义的打开文件的方法 } }); openMultipleButton.setOnAction(//打开多文件按钮事件处理机制 (final ActionEvent e) -> { configureFileChooser(fileChooser);//自定义方法配置文件选择器对象 List list = fileChooser.showOpenMultipleDialog(stage);//在当前舞台对象环境下打开文件多文件选择器对话框 if (list != null) { list.stream().forEach((file) -> {//循环迭代选择的多文件路径列表,依次循环打开所选的文件 openFile(file); }); } }); final GridPane inputGridPane = new GridPane();//格子布局面板对象 GridPane.setConstraints(openButton, 0, 0);//第一个打开按钮约定放在第一行第一列 GridPane.setConstraints(openMultipleButton, 1, 0);//第二个打开多文件按钮约定放在第一行第二列 inputGridPane.setHgap(6);//设置布局表格的水平间距为6 inputGridPane.setVgap(6);//设置布局表格的垂直间距为6 inputGridPane.getChildren().addAll(openButton, openMultipleButton);//布局面板对象上面添加此两个按钮 final Pane rootGroup = new VBox(12);//创建一个垂直盒子布局器 rootGroup.getChildren().addAll(inputGridPane);//垂直盒子布局器上添加表格布局器对象 rootGroup.setPadding(new Insets(12, 12, 12, 12));//设置垂直盒子布局器的内边距,利用Insets类型填充物对象来作为内边距的填充 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("请选择你想要的文件");//设置文件选择器打开时候的提示标题 fileChooser.setInitialDirectory(//设置文件选择器的初始化打开目录 new File(System.getProperty("user.home"))//引向操作系统的用户名目录 ); } private void openFile(File file) { EventQueue.invokeLater(() -> {//引用操作系统事件队列调用响应机制 try { desktop.open(file);//桌面运行环境下打开指定的文件 } catch (IOException ex) { ex.printStackTrace(); } }); } }

configureFileChooser方法将标题设置为了“请选择你想要的文件” 并且将文件路径指定为用户目录

——————————————————————————————

你也可以让用户通过使用DirectoryChooser类来选择目标目录

import javafx.application.Application; import javafx.event.ActionEvent; 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.DirectoryChooser; import javafx.stage.FileChooser; import javafx.stage.Stage; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.List; public final class FileChooserTest2 extends Application { private final Desktop desktop = Desktop.getDesktop();//获取并创建当前操作系统桌面应用环境对象 @Override public void start(final Stage stage) { stage.setTitle("文件选择器示例"); final FileChooser fileChooser = new FileChooser();//创建一个文件选择器对象 final Button openButton = new Button("打开一个文件_按钮"); final Button openMultipleButton = new Button("打开多个文件_按钮"); final Button browseButton = new Button("浏览");//创建浏览按钮 browseButton.setOnAction( (final ActionEvent e) -> { final DirectoryChooser directoryChooser = new DirectoryChooser();//创建目录选择器对象 final File selectedDirectory = directoryChooser.showDialog(stage);//在本舞台对象环境下获取目录选择器对象所选择的文件路径的引用 if (selectedDirectory != null) { selectedDirectory.getAbsolutePath();//如果路径不为空则获取绝对路径 } }); openButton.setOnAction(//打开文件按钮事件处理机制 (final ActionEvent e) -> { configureFileChooser(fileChooser);//自定义方法配置文件选择器对象 File file = fileChooser.showOpenDialog(stage);//在当前舞台对象环境下打开文件选择器对话框 if (file != null) {//如果文件路径不为空则打开文件 openFile(file);//自定义的打开文件的方法 } }); openMultipleButton.setOnAction(//打开多文件按钮事件处理机制 (final ActionEvent e) -> { configureFileChooser(fileChooser);//自定义方法配置文件选择器对象 List list = fileChooser.showOpenMultipleDialog(stage);//在当前舞台对象环境下打开文件多文件选择器对话框 if (list != null) { list.stream().forEach((file) -> {//循环迭代选择的多文件路径列表,依次循环打开所选的文件 openFile(file); }); } }); final GridPane inputGridPane = new GridPane();//格子布局面板对象 GridPane.setConstraints(openButton, 0, 0);//第一个打开按钮约定放在第一行第一列 GridPane.setConstraints(openMultipleButton, 1, 0);//第二个打开多文件按钮约定放在第一行第二列 GridPane.setConstraints(browseButton, 2, 0);//第二个打开多文件按钮约定放在第一行第二列 inputGridPane.setHgap(6);//设置布局表格的水平间距为6 inputGridPane.setVgap(6);//设置布局表格的垂直间距为6 inputGridPane.getChildren().addAll(openButton, openMultipleButton,browseButton);//布局面板对象上面添加此两个按钮 final Pane rootGroup = new VBox(12);//创建一个垂直盒子布局器 rootGroup.getChildren().addAll(inputGridPane);//垂直盒子布局器上添加表格布局器对象 rootGroup.setPadding(new Insets(12, 12, 12, 12));//设置垂直盒子布局器的内边距,利用Insets类型填充物对象来作为内边距的填充 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("请选择你想要的文件");//设置文件选择器打开时候的提示标题 fileChooser.setInitialDirectory(//设置文件选择器的初始化打开目录 new File(System.getProperty("user.home"))//引向操作系统的用户名目录 ); } private void openFile(File file) { EventQueue.invokeLater(() -> {//引用操作系统事件队列调用响应机制 try { desktop.open(file);//桌面运行环境下打开指定的文件 } catch (IOException ex) { ex.printStackTrace(); } }); } }

在作出了选择之后,你可以使用如下的代码来将对应的值分配给文件选择框:fileChooser.setInitialDirectory(selectedDirectory);

————————————————————————

设置扩展名过滤器(ExtensionFilter)

根据下面的配置项,你可以设置扩展名过滤器(ExtensionFilter)来决定哪些文件可以在文件选择框中可以被打开 

设置一个图片类型过滤器 

你使用FileChooser.ExtensionFilter来设置了一个extension filter,它定义了这些文件类型是可以选择的:所有的图片文件、JPG和PNG

点击其中的一个按钮,对应的扩展名过滤器将会出现在文件选择框窗体中。如果一个用户选择了JPG,那么在文件选择框中将会仅显示JPG类型的图片 

import java.awt.*; 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.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 FileChooserPicture extends Application { private final Desktop desktop = Desktop.getDesktop();//windows桌面对象(本机windows操作系统桌面对象的获取) @Override public void start(final Stage stage) { stage.setTitle("FileChooser过滤器例子"); final FileChooser fileChooser = new FileChooser();//创建一个文件选择器对象 final Button openButton = new Button("选择图片"); final Button openMultipleButton = new Button("打开多个按钮"); openButton.setOnAction(//按钮点击事件处理函数 (final ActionEvent e) -> { configureFileChooser(fileChooser);//配置文件选择器组件 File file = fileChooser.showOpenDialog(stage);//在指定的舞台对象上打开文件打开对话框,并选取所选文件 if (file != null) { openFile(file);//打开文件操作 } }); openMultipleButton.setOnAction( (final ActionEvent e) -> { configureFileChooser(fileChooser);//配置文件选择器组件 List list = fileChooser.showOpenMultipleDialog(stage);//在指定的舞台对象上打开多选文件打开对话框,并选取所选文件列表 if (list != null) { list.stream().forEach((file) -> {//循环逐一打开所选文件 openFile(file); }); } }); final GridPane inputGridPane = new GridPane();//创建个网格布局面板 GridPane.setConstraints(openButton, 0, 1);//设置按钮一布局在第二行第一列位置的约束 GridPane.setConstraints(openMultipleButton, 1, 1);//设置按钮二布局在第二行第二列位置的约束 inputGridPane.setHgap(6);//设置网格中元素的水平间距为6 inputGridPane.setVgap(6);//设置网格中元素的垂直间距为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("查看图片");//设置文件选择器标题 fileChooser.setInitialDirectory(//默认打开底层操作系统指定的用户目录 new File(System.getProperty("user.home")) ); fileChooser.getExtensionFilters().addAll(//设置文件选择器所能打开的文件类型(利用给文件选择器对象添加扩展名过滤器功能来实现) new FileChooser.ExtensionFilter("All Images", "*.*"),//所有格式类型过滤器 new FileChooser.ExtensionFilter("JPG", "*.jpg"),//.jpg图片格式类型过滤器 new FileChooser.ExtensionFilter("PNG", "*.png")//.png图片格式类型过滤器 ); } private void openFile(File file) {//打开文件的方法 EventQueue.invokeLater(() -> {//操作系统事件队列执行调用器 try { desktop.open(file);//从桌面珊打开文件 } catch (IOException ex) { Logger.getLogger(FileChooserPicture. class.getName()). log(Level.SEVERE, null, ex); } }); } }

保存文件

除了打开和过滤文件,FileChooser API还提供了让用户指定一个文件名(及其在文件系统中的位置)来在应用程序中保存文件。FileChooser类的showSaveDialog方法会打开一个保存对话框窗体。与其他展示对话框的方法一样,showSaveDialog方法返回了被用户选择的文件或者当没有作出选择时返回null。

import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.effect.DropShadow; import javafx.scene.effect.Effect; import javafx.scene.effect.Glow; import javafx.scene.effect.SepiaTone; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; import javax.imageio.ImageIO; import java.io.File; import java.io.IOException; import java.util.AbstractMap.SimpleEntry; import java.util.Map.Entry; public class MenuSample extends Application { final PageData[] pages = new PageData[]{ new PageData("标题一", "描述一", "名称一"), new PageData("标题二", "描述二", "名称二"), new PageData("标题三", "描述三", "名称三"), new PageData("标题", "描述", "名称") }; final String[] viewOptions = new String[]{ "标题", "二项式", "图片", "描述" }; final Entry[] effects = new Entry[]{//Entry类型数组对象的初始化 new SimpleEntry("褐色特效", new SepiaTone()),//创建一个深褐色特效 用SimpleEntry类型对象保存,key是String 而value 是特效对象 new SimpleEntry("发光特效", new Glow()),//创建一个发光特效,用SimpleEntry类型对象保存,key是String 而value 是特效对象 new SimpleEntry("阴影特效", new DropShadow())//创建一个阴影特效,用SimpleEntry类型对象保存,key是String 而value 是特效对象 }; final ImageView pic = new ImageView();//创建视图显示区域 final Label name = new Label();//创建标签对象 final Label binName = new Label();//创建标签对象 final Label description = new Label();//创建标签对象 private int currentIndex = -1;//当前下标值的初始化设置 public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) { stage.setTitle("Menu例子"); Image image = new Image("https://www.dllg56.com/qt/img/logo-sing.png"); stage.getIcons().add(image); Scene scene = new Scene(new VBox(), 400, 350);//创建一个场景对象,并将场景上挂载一个垂直盒子Vbox布局对象 final VBox vbox = new VBox();//创建一个垂直布局对象 vbox.setAlignment(Pos.CENTER);//设置vbox对象对齐方式 vbox.setSpacing(10);//设置vbox对象布局的元素之间的空间距离 vbox.setPadding(new Insets(0, 10, 0, 10));//设置Vbox对象内边距 vbox.getChildren().addAll(name, binName, pic, description);//vbox布局器中要添加的被布局元素对象(用vbox对象布局相关Node类型Label标签型对象和ImageView类型对象) shuffle();//清晰复原程序 MenuBar menuBar = new MenuBar();//创建一个MenuBar类型对象 // --- Menu File Menu menuFile = new Menu("Menu选择图片"); // --- Menu Edit Menu menuEdit = new Menu("Menu图片编辑"); // --- Menu View Menu menuView = new Menu("Menu菜单三"); //将上文创建的三个Menu对象添加(镶嵌)到MenuBar对象上去 menuBar.getMenus().addAll(menuFile, menuEdit, menuView);//Menu类型对象都是要镶嵌在MenuBar对象上的 final ContextMenu cm = new ContextMenu();//创建内置上下文菜单 MenuItem cmItem1 = new MenuItem("复制图片");//创建菜单选项MenuItem类型对象 cmItem1.setOnAction((ActionEvent e) -> { Clipboard clipboard = Clipboard.getSystemClipboard();//获取操作系统的剪贴板 ClipboardContent content = new ClipboardContent();//创建剪贴板内容 content.putImage(pic.getImage());//剪贴板内容对象中添加上文定义的图片 clipboard.setContent(content);//剪贴板对象中挂载剪贴板内容对象 }); pic.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {//图片点击鼠标事件处理回调函数的编写 if (e.getButton() == MouseButton.SECONDARY){//当该鼠标点击事件是鼠标右键触发时,显示剪贴板中的内容 cm.show(pic, e.getScreenX(), e.getScreenY());}//在将创建的ContextMenu类型内置上下文菜单展示右键按钮所在的横纵坐标位置处 }); MenuItem cmItem2 = new MenuItem("保存图片");//创建一个菜单选项 cmItem2.setOnAction((ActionEvent e) -> {//给菜单选项cmItem2上添加鼠标交互事件处理机制回调函数 FileChooser fileChooser1 = new FileChooser();//创建一个文件选择器对象 configureFileChooser(fileChooser1);//配置文件选择器组件 fileChooser1.setTitle("Save Image");//设置文件选择器的标题 System.out.println(pic.getId());//打印图片对象的id标识 File file = fileChooser1.showSaveDialog(stage);//打开文件保存对话框,并获取所选中的路径 if (file != null) { try { ImageIO.write(SwingFXUtils.fromFXImage(pic.getImage(), null), "jpg", file);//将文件以指定的jpg格式写到file所指定的路径上去保存 } catch (IOException ex) { System.out.println(ex.getMessage()); } } }); cm.getItems().addAll(cmItem1,cmItem2);//内嵌上下文菜单中添加多个菜单选项 Menu menuEffect = new Menu("图片特效");//创建一个菜单(后续作为子菜单) final ToggleGroup groupEffect = new ToggleGroup();//创建一个互斥切换组对象 for (Entry effect : effects) {//遍历保存了图形特效的List类型对象 RadioMenuItem itemEffect = new RadioMenuItem(effect.getKey());//创建一个RadioMenuItem类型菜单选项对象 itemEffect.setUserData(effect.getValue());//将从SimpleEntry类型对象中获取的vlaue值(Effect类型图像特效对象)作为用户选择数据项内容设置给RadioMenuItem类型对象的用户选择数据内容 itemEffect.setToggleGroup(groupEffect);//将RadioMenuItem类型对象添加到一个互斥组对象中去 menuEffect.getItems().add(itemEffect);//将RadioMenuItem类型对象作为选下挂载到前文定义的 图片特效子菜单中 } //No Effects菜单 final MenuItem noEffects = new MenuItem("无特效");//创建一个普通菜单选项MenuItem类型对象 noEffects.setDisable(true);// 初始化无特效菜单选项是被禁用的 noEffects.setOnAction((ActionEvent t) -> {//给上文定义的菜单选项对象添加交互事件处理回调函数 pic.setEffect(null);//将ImageView类型对象pic的特效设置为null groupEffect.getSelectedToggle().setSelected(false);//将互斥组ToggleGroup类型对象groupEffect的被选中项的对象对应的选中状态设置为false未选状态 noEffects.setDisable(true);//引用无特效选项 }); //处理菜单项的选中事件 groupEffect.selectedToggleProperty().addListener(new ChangeListener() {//ToggleGroup类型对象的互斥选项,选项选中改变交互事件处理回调函数的编写 public void changed(ObservableValue


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有