What Will I Learn?
In this tutorial;
- You will learn how to add a file chooser dialog box in a Java GUI.
- You will learn the JFileChooser class.
- You will learn the JTextField class.
- You will learn how to read and show the selected file.
Requirements
-Java SE Development Kit (Not necessarily the last version) is required.
-Eclipse IDE or any similar Interated Development Enviroment (IDE) that is designed for Java programming language is required.
Difficulty
- Intermediate
Tutorial Contents
The purpose of this tutorial is to show the use of file choosers in Java. The demo program for the file choosers contains a single Java file (File_Choosers_Demo.java). The following figure contains the code of the Java file.
For this demo program, we have the text file that contains the code of the demo program. The following figure contains the image of text file.
When the demo program asks the file to choose with file chooser to the user of the program, this text file is going to be chosen. It is expexted to see this text file in the frame that is going to open after chosen the file.
In this demo program, we need to import the necessary packages for IOException, the Scanner Class and GUI components (JFrame, JTextArea and JFileChooser).
import java.util.Scanner; //For the Scanner Class
import java.io.*; //For the IOException
import javax.swing.*; // For GUI Components
Since this demo program is going to deal with the files, the throw IOExeception should be added into the definition part of the main method to prevent the errors that can be caused because of the file related problems such as selecting an inappropriate file.
public class File_Choosers_Demo {
public static void main(String[] args) throws IOException {
After defining the main method, the frame that is going to open after file selection should be defined.
JFrame frame = new JFrame("File Chooser Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea
JTextArea is similar to the JTextFile. The difference is that the JTextArea can display multiple lines of a text at one time unlike the JTextField. A text field takes the width in column and the height in rows as initial parametes. To construct a text area that has 30 rows height and 30 columns width, you need to use the following code;
JTextArea text_area = new JTextArea(30, 30);
JFileChooser
The JFileChooser class gives us a specialized dialog box that allows us to choose a file from the computer which runs the program. It does not take any parameters in its constractor. You can defina a file chooser object with following code;
JFileChooser file_chooser = new JFileChooser();
With the showOpenDialog method, the file chooser opens to user. You can directly take the result of this methods as integer to check the status of the file choser because the showOpenDialog method returns an integer value that represents the status of file choser.
int check_status = file_chooser.showOpenDialog(null);
At this point the file chooser is visible to the user. Now, we need to check whether the file is chosen or not. When the user select the file, the special method of the JFileChoose class which is APPROVE_OPTION returns the same integer value with the showOpenDialog. Therefore we can check the status of the file chooser with the following else if statements.
if(check_status != JFileChooser.APPROVE_OPTION)
text_area.setText("No File Chosen");
else {
The code after else statement will be executed if the file is chosen. Note that No file chosen means that the cancel button is selected by user.
getSelectedFile Method
The getSelectedFile method is the method that allows us to get the chosen file as file variable in Java. You can get the chosen file from the file chooser with the following code;
File chosen_file = file_chooser.getSelectedFile();
At this point the selected text file is taken by the program as file object. Now, with the following code, the file is read line by line and finally added to the text area. Since reading text files in Java is explained in one of my previous tutorials, it will not be explanined again. You can find the tutorial about reading text files in here.
Scanner scan = new Scanner(chosen_file);
String text = "";
while(scan.hasNext())
text+=scan.nextLine()+"\n";
text_area.setText(text);
Results
When you run the program, the file chooser opens as you can see in the below figures.
If the user selects the code.txt file and presses the open button, the File Chooser Demo frame opens with the codes with the code.txt file in the text area. You can see the images of this in below figures.
If the user presses the cancel button, the File Chooser Demo frame opens with No File Chosen text in the text area. You can see the images of this in below figures.
If the user selects a file which is not .txt form, the programs does not give any error shows empty text area since we used the IOException in the code.
Github
You can get this program from Github.
Code of the Program
import java.util.Scanner;
import java.io.*;
import javax.swing.*;
public class File_Choosers_Demo {
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("File Chooser Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea text_area = new JTextArea(30, 30);
JFileChooser file_chooser = new JFileChooser();
int check_status = file_chooser.showOpenDialog(null);
if(check_status != JFileChooser.APPROVE_OPTION)
text_area.setText("No File Chosen");
else {
File chosen_file = file_chooser.getSelectedFile();
Scanner scan = new Scanner(chosen_file);
String text = "";
while(scan.hasNext())
text+=scan.nextLine()+"\n";
text_area.setText(text);
}
frame.getContentPane().add(text_area);
frame.pack();
frame.setVisible(true);
}
}
Curriculum
You can find my other java related tutorials in below links.
- Adding JPEG or GIF image files into the GUI in Java using Eclipse IDE
- Reading Text Files and Parsing It Using Iterators and Delimiter in Java with Eclipse IDE
- Drawing Methods in Java Applet (JApplet) Using Eclipse IDE: Drawing a Snowman
- Check Boxes (JCheckBox) and Its Listeners in a Java GUI using Eclipse IDE
- Use of Layout Managers and Tabbed Pane in Java Using Eclipse IDE
- Use of Borders in a Java GUI Using Eclipse IDE
Posted on Utopian.io - Rewarding Open Source Contributors
Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
Hey @aromatheraphy I am @utopian-io. I have just upvoted you!
Achievements
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x