- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to save files using a File Chooser in JavaFX?
Using JavaFX file chooser, you can open files browse through them and save the files. The class javafx.stage.FileChooser represents a file chooser, you can open a file dialog open single or multiple files using this. You can create a file chooser in your application by instantiating this class.
Opening multiple files
The showSaveDialog() method displays a save dialog which allows you to save a file and return it. This method returns null if you haven’t chosen any file
To save a file using JavaFX −
Instantiate the FileChooser class.
Set the required properties.
Invoke the showSaveDialog() method.
Add the file chooser to a root node.
Add the root node to the scene object
Example
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); } }
Output
Advertisements