Java Save Dialog Box Example

Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

How to Show Open Save File Dialog in Java Swing Application? JFileChooser Example

Hello guys, if you worked in Java GUI-based application then you may know that Swing provides class javax.swing.JFileChoosercan be used to present a dialog for the user to choose a location and type a file name to be saved, using the showSaveDialog() method. Syntax of this method is as follows:

                public                int                showSaveDialog(Component                parent)

where the parent is the parent component of the dialog, such as a JFrame.
Once the user typed a file name and select OK or Cancel, the method returns one of the following value:

JFileChooser.CANCEL_OPTION:                  the                  user cancels                  file                  selection. JFileChooser.APPROVE_OPTION:                  the                  user accepts                  file                  selection. JFileChooser.ERROR_OPTION:                  if                  there's                  an                  error                  or                  the                  user                             closes                  the                  dialog                  by                  clicking                  on                  the                  X                  button.

After the dialog is dismissed and the user approved a selection, you can use the getSelectedFile() methods to get the selected file:

Also, it's worth noting that before calling the showSaveDialog() method, you may want to set some options for the dialog. You can use the setDialogTitle(String)  method to set a custom title text for the dialog and setCurrentDirectory(File) to set the directory where it will be saved.

Btw, I am expecting that you are familiar with Java programming language and basic Java APIs like java.lang and java.util package. If you are a complete beginner, I suggest you first go through a comprehensive Java course to build your concepts.

If you need a recommendation, The Complete Java Masterclass by Tim Buchalaka on Udemy is a great course to start with. It's also the most up-to-date and covers new Java features from recent Java releases.

Java Program to use JFileChooser in Swing - Example

Here is a complete Java program that demonstrates how to use the file chooser class from the Swing package. You can just copy-paste the code and run it in your favorite IDE like Eclipse, NetBeans, or IntelliJIDEA. You don't need to add any third-party library because swing comes along JDK itself.

package test;

                import                java.awt.BorderLayout;                import                java.awt.FlowLayout;                import                java.awt.event.ActionEvent;                import                java.awt.event.ActionListener;                import                java.io.File;                import                javax.swing.JButton;                import                javax.swing.JFileChooser;                import                javax.swing.JFrame;                import                javax.swing.SwingUtilities;                import                javax.swing.UIManager;                import                javax.swing.UnsupportedLookAndFeelException;                /** * Java program to demonstrate how to use JFileChooser for showing open file * dialog and save file dialog in Java application.  */                public                class                Test                extends                JFrame {                private                final                JButton                upload                =                new                JButton("Upload");                private                final                JButton                save                =                new                JButton("Save");                public                Test() {         super("JFileChooser Example - Open Save File Dialong in Java");         setLayout(new                FlowLayout());         upload.addActionListener(new                ActionListener() {                @Override                public                void                actionPerformed(ActionEvent                arg0) {                 showSelectFileDialong();             }         });         getContentPane().add(upload);         setSize(300, 100);         setDefaultCloseOperation(JFrame                .EXIT_ON_CLOSE);         setVisible(true);     }                public                static                void                main(String[] args) {                try                {                UIManager                .setLookAndFeel(UIManager                .getSystemLookAndFeelClassName());         }                catch                (ClassNotFoundException                                  |                InstantiationException                                |                IllegalAccessException                                  |                UnsupportedLookAndFeelException                e) {         }                SwingUtilities                .invokeLater(new                Runnable() {                @Override                public                void                run() {                Test                t                =                new                Test();             }         });     }                private                void                showSelectFileDialong() {                JFileChooser                fileChooser                =                new                JFileChooser();         fileChooser.setDialogTitle("Choose a File to upload");                // pass reference of your JFrame here                int                response                =                fileChooser.showSaveDialog(this);                if                (response                ==                JFileChooser                .APPROVE_OPTION) {                File                selectedFile                =                fileChooser.getSelectedFile();                System                .out.println("Save as file: "                                  +                selectedFile.getAbsolutePath());         }     }   }

How to run this Java Swing Program? Example

As I said, this program is complete in itself. You can just copy-paste and run in your favorite IDE. Just make sure that you keep the name of the source file the same as the public class. If you use Eclipse then you don't even need to do that because Eclipse will automatically create the file with the same name.

You also don't need any third-party library because Swing is part of JDK. When you run this program it will start a Swing application and you will see a JFrame window as shown below

You can see the upload button, when you click on the button it will open the native file chooser option which will allow you to choose the file and folder you want to upload as shown in the following screenshot:

That's all about how to use the JFileChooser class in the Java Swing application. It's one of the most useful and common components of Java Swing API and you will often find using it Java GUI application. Just make you understand the different API methods to customize the look and feel of the window and also how to get the name and other attributes of the chosen file to do the next action like saving into a database or any other directory.

Other Java Swing Tutorials and Interview Questions You may find useful

  • Is Swing Components Thread-Safe in Java? (answer)
  • Difference between invokeAndWait() and invokeLater() in Java? (answer)
  • Top 10 AWT Swing Interview Questions with Answers (answer)
  • How to close a Swing Application in Java? (answer)
  • How to use List in Java Swing Application (tutorial)
  • What is a blocking method in Java? (answer)
  • 12 Java Books for Experienced Developers (books)
  • Best books and Mock Exam for OCAJP 8 Certification (guide)
  • Difference between repaint() and revalidate() method in swing? (answer)
  • 10 Java Swing Interview questions for GUI developers (questions)

Thanks for reading this article so far. If you find this Java Swing tutorial useful then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note. If you want to learn more about the Swing framework then Java: The Complete Reference, Ninth Edition is worth reading.


barbiericous1984.blogspot.com

Source: https://www.java67.com/2020/04/jfilechooser-example-show-open-save-file-dialong-java-swing.html

0 Response to "Java Save Dialog Box Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel