如何使用 JavaFX 中的文件选择器保存文件?
使用 JavaFX 文件选择器可以打开文件、浏览文件并保存文件。类 javafx.stage.FileChooser 表示一个文件选择器,可以使用它打开文件对话框打开单个文件或多个文件。你可以通过实例化此类在你的应用程序中创建一个文件选择器。
打开多个文件
showSaveDialog() 方法显示一个允许保存文件并返回它的保存对话框。如果你未选择任何文件,此方法将返回 null
使用 JavaFX 保存文件 -
实例化 FileChooser 类。
设置所需属性。
调用 showSaveDialog() 方法。
将文件选择器添加到根节点。
将根节点添加到场景对象
示例
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.FileChooser.ExtensionFilter;
public class FileChooserSavingFile extends Application {
@Override
public void start(Stage stage) {
ImageView imgView = new ImageView("UIControls/Save.png");
imgView.setFitWidth(20);
imgView.setFitHeight(20);
Menu file = new Menu("File");
MenuItem item = new MenuItem("Save", imgView);
file.getItems().addAll(item);
//Creating a File chooser
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save");
fileChooser.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*.*"));
//Adding action on the menu item
item.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
//Opening a dialog box
fileChooser.showSaveDialog(stage);
}
});
//Creating a menu bar and adding menu to it.
MenuBar menuBar = new MenuBar(file);
Group root = new Group(menuBar);
Scene scene = new Scene(root, 595, 355, Color.BEIGE);
stage.setTitle("File Chooser Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP