FahmidasClassroom

Learn by easy steps

Editor

You have to complete the design of the text editor by using JFrame and JMenu that has been on “Create Menu using Java” tutorial before starting this tutorial. The way of creating a new file, opening any existing text file, and save the content into a text file have been shown in this tutorial.

Step-1:

Open the Java project that has been created in the previous tutorial that contains three menu items. These are File, Edit, and Format. File menu contains four menu items. These are New, Open, Save, and Exit.

Step-2:

Import the following packages.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;

Step-3:

Double click on the Exit menu item and add the following code to terminate from the application.

//Terminate from the application
System.exit(0);

Step-4:

Double click on the Open menu item and add the following code to open any text file.

//Create an object of JFileChooser
JFileChooser fc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
//Disable the selection of all file types
fc.setAcceptAllFileFilterUsed(false);
//Set the filter for all text files only
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
//Use the filter for the jFileChooser        
fc.addChoosableFileFilter(filter);

//Open the open dialog box
int returnValue = fc.showOpenDialog(null);

//Check Open button is selected or not
if (returnValue == JFileChooser.APPROVE_OPTION) 
{
     BufferedReader br = null;
     try 
     {
         //Get the selected file
         File selectedFile = fc.getSelectedFile();
         //Read the file path 
         File file = new File(selectedFile.getAbsolutePath());
         //Create the object of BufferedReader class
         br = new BufferedReader(new FileReader(file));
         //Declare an empty string variable that will store the file content
         String st="";
         //Declare a string variable that will read each line 
         String line;
         //Read the file line by line by using the loop
         while ((line = br.readLine()) != null)
              //Store the file content into the variable
              st = st+line+"\n";
         jTextArea1.setText(st);
      } catch (FileNotFoundException ex) {
          Logger.getLogger(JMenu.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IOException ex) {
          Logger.getLogger(JMenu.class.getName()).log(Level.SEVERE, null, ex);
      } finally {
          try {
             br.close();
          } catch (IOException ex) {
             Logger.getLogger(JMenu.class.getName()).log(Level.SEVERE, null, ex);
          }
      }
}

Step-5:

Double click on the Save menu item and add the following code to sane the content of the text editor in to a text file.

//Create an object of JFileChooser
JFileChooser fc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());

//Set the filter for all text files 
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
//Use the filter for the jFileChooser        
fc.addChoosableFileFilter(filter);
//Open the dialog box
int returnValue = fc.showSaveDialog(null);

//Check Save button is selected or not
if (returnValue == JFileChooser.APPROVE_OPTION) 
{
     //Assign the selected file
     File selectedFile = fc.getSelectedFile();
     //Create the instance of file
     Path path = Paths.get(selectedFile.getAbsolutePath());
     //Read the content of the text editor
     String str = jTextArea1.getText();

     //Convert string to byte array using getBytes() method
     byte[] arr = str.getBytes();

     //Try block to check for exceptions
     try {
         //Write to the file by using pathnand byte array
         Files.write(path, arr);
     }

     //Catch block to handle the exceptions
     catch (IOException ex) {
         //Print message as exception occurred 
         System.out.print("Invalid Path");
     }
}

Step-6:

Double click on the New menu item and add the following code to clear the editor.

//Clear the text area
jTextArea1.setText("");

Step-7:

Run the application.