Build a text editor using Java swing

Hi, we are learning how to build a text editor using Java or we can say a simple notepad. Java swing components are lightweight as compared to other GUI components of Java. It is also platform-independent.

So let’s discuss how to build this project using Java swing. First, let’s discuss the components required to build this project are Text area require to writing or reading the text, then we require some menu items like file, edit, and info file contains options like open, save, new and exit whereas edit contains cut, copy, paste, undo and redo and finally on info contains information about developer and text editor. Now we require a scroll bar that scrolls the page according to the requirement of the user. Now we need to add functionality to each menu item to cut, copy, and past we require only one line of code as given below respectively.

textArea.cut();
textArea.copy();
textArea.paste();

Where textArea is the object of the JTextArea which is used for the Text Area component. Now we require to add undo and redo functionality so we require to create an object of UndoManager class and then attach this object with textArea.

UndoManager undo = new UndoManager();
textArea.getDocument().addUndoableEditListener(undo);

Now use this object and add undo and redo functionality to the menu items by writing a single line of code for each one.

undo.undo();
undo.redo();

Next, we require to add functionality to new, open, save and exit menu items. Let’s being with new for it we just need to clear the text in the teaxtArea component so for that, we need to set the empty string in it.

textArea.setText(" ");

Now it time to save and open both of them the code require to add functionality in them is similar. First, we will code for the functionality to save a file.

JFileChooser filechooser = new JFileChooser("f:");
int temp = filechooser.showSaveDialog(null);
if (temp == JFileChooser.APPROVE_OPTION) {
File file = new File(filechooser.getSelectedFile().getAbsolutePath());
try {
      FileWriter filewriter = new FileWriter(file, false);
      BufferedWriter bufferwr = new BufferedWriter(filewriter);
      bufferwr.write(textRegion.getText());
      bufferwr.flush();
      bufferwr.close();
    }
 catch (Exception ex) {
                       JOptionPane.showMessageDialog(frmTextEditor, ex.getMessage());
}
}

Now we will code for opening a file in the text editor.

JFileChooser filechooser = new JFileChooser("f:");
              int temp = filechooser.showOpenDialog(null);
    
              if (temp == JFileChooser.APPROVE_OPTION) {
                  File file = new File(filechooser.getSelectedFile().getAbsolutePath());
    
                  try {
                  	String str="",str1="";
                  	FileReader fileread = new FileReader(file);
                  	BufferedReader bufferrd = new BufferedReader(fileread);
                  	str1=bufferrd.readLine();
                  	while((str=bufferrd.readLine())!=null) {
                  		str1=str1+"\n"+str;
                  	}
                  	textRegion.setText(str1);
                  }
                  catch(Exception ex) {
                  	JOptionPane.showMessageDialog(frmTextEditor, ex.getMessage());
                  }
                  }

Now finally we will code for exiting from the text editor through the exit menu item.

frmTextEditor.dispatchEvent(new WindowEvent(frmTextEditor, WindowEvent.WINDOW_CLOSING));

finally, we discuss the major and some minor parts of the code of the project so to completely deploy or build this project we require complete code which is attached below just copy it and build your own text editor.

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;

import java.awt.CardLayout;
import javax.swing.JTextArea;
import javax.swing.SpringLayout;
import javax.swing.undo.UndoManager;

import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.awt.event.ActionEvent;
import javax.swing.BoxLayout;
import java.awt.BorderLayout;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;

public class text_editor {

  private JFrame frmTextEditor;

  /**
   * Launch the application.
   */
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        try {
          text_editor window = new text_editor();
          window.frmTextEditor.setVisible(true);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
  }

  /**
   * Create the application.
   */
  public text_editor() {
    initialize();
  }

  /**
   * Initialize the contents of the frame.
   */
  private void initialize() {
    frmTextEditor = new JFrame();
    frmTextEditor.setTitle("Text Editor");
    frmTextEditor.setBounds(100, 100, 505, 490);
    frmTextEditor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTextEditor.getContentPane().setLayout(new BorderLayout(0, 0));
    
    JTextArea textRegion = new JTextArea();
    frmTextEditor.getContentPane().add(textRegion, BorderLayout.CENTER);
    JMenuBar menuBar = new JMenuBar();
    frmTextEditor.setJMenuBar(menuBar);
    UndoManager undo = new UndoManager();
    textRegion.getDocument().addUndoableEditListener(undo);
    JMenu mnFile = new JMenu("File");
    menuBar.add(mnFile);
    
    JMenuItem mntmNew = new JMenuItem("New");
    mntmNew.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
        textRegion.setText("");
      }
    });
    mnFile.add(mntmNew);
    
    JMenuItem mntmSave = new JMenuItem("Save");
    mntmSave.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        JFileChooser filechooser = new JFileChooser("f:");
              int temp = filechooser.showSaveDialog(null);
    
              if (temp == JFileChooser.APPROVE_OPTION) {
                  File file = new File(filechooser.getSelectedFile().getAbsolutePath());
    
                  try {
                      FileWriter filewriter = new FileWriter(file, false);
                      BufferedWriter bufferwr = new BufferedWriter(filewriter);
                      bufferwr.write(textRegion.getText());
                      bufferwr.flush();
                      bufferwr.close();
                  }
                  catch (Exception ex) {
                      JOptionPane.showMessageDialog(frmTextEditor, ex.getMessage());
                  }}
      }
    });
    mnFile.add(mntmSave);
    
    JMenuItem mntmOpen = new JMenuItem("Open");
    mntmOpen.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        JFileChooser filechooser = new JFileChooser("f:");
              int temp = filechooser.showOpenDialog(null);
    
              if (temp == JFileChooser.APPROVE_OPTION) {
                  File file = new File(filechooser.getSelectedFile().getAbsolutePath());
    
                  try {
                  	String str="",str1="";
                  	FileReader fileread = new FileReader(file);
                  	BufferedReader bufferrd = new BufferedReader(fileread);
                  	str1=bufferrd.readLine();
                  	while((str=bufferrd.readLine())!=null) {
                  		str1=str1+"\n"+str;
                  	}
                  	textRegion.setText(str1);
                  }
                  catch(Exception ex) {
                  	JOptionPane.showMessageDialog(frmTextEditor, ex.getMessage());
                  }
                  }
              }	                
      
    });
    mnFile.add(mntmOpen);
    
    JMenuItem mntmExit = new JMenuItem("Exit");
    mntmExit.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        frmTextEditor.dispatchEvent(new WindowEvent(frmTextEditor, WindowEvent.WINDOW_CLOSING));
      }
    });
    mnFile.add(mntmExit);
    
    JMenu mnEdit = new JMenu("Edit");
    menuBar.add(mnEdit);
    
    JMenuItem mntmCut = new JMenuItem("Cut");
    mntmCut.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        textRegion.cut();
      }
    });
    mnEdit.add(mntmCut);
    
    JMenuItem mntmCopy = new JMenuItem("Copy");
    mntmCopy.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        textRegion.copy();
      }
    });
    mnEdit.add(mntmCopy);
    
    JMenuItem mntmExi = new JMenuItem("Paste");
    mntmExi.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        textRegion.paste();
      }
    });
    mnEdit.add(mntmExi);
    
    JMenuItem mntmUndo = new JMenuItem("Undo");
    mntmUndo.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        undo.undo();
      }
    });
    mnEdit.add(mntmUndo);
    
    JMenuItem mntmRedo = new JMenuItem("Redo");
    mntmRedo.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        undo.redo();
      }
    });
    mnEdit.add(mntmRedo);
    
    JMenu mnInfo = new JMenu("Info");
    menuBar.add(mnInfo);
    
    JLabel lblThisEditorIs = new JLabel("This Editor is designed in Java Swing");
    mnInfo.add(lblThisEditorIs);
    
    JSeparator separator = new JSeparator();
    mnInfo.add(separator);
    
    JLabel lblDevelopedByYashika = new JLabel("& Developed By Yashika Jain");
    mnInfo.add(lblDevelopedByYashika);		
     JScrollPane scrollabletextRegion = new JScrollPane(textRegion);  
     scrollabletextRegion.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
          scrollabletextRegion.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);  
          frmTextEditor.getContentPane().add(scrollabletextRegion);  
    
    
    
  }
}

Thank you for reading this Blog.

Also read: Create an image slider in Java Swing

Leave a Reply

Your email address will not be published. Required fields are marked *