How to Create Notepad in Java

Free Java courses with 37 real-time projects - Learn Java

Notepad is a simple software that is used by users on a daily basis. Users can use a notepad for noting down the important notes, to-dos, writing codes, etc. Some users use notepads for diary writing, story writing, etc.

About Notepad Project

We will develop following functionalities in Java Notepad

  • Users can create new text files and note down the notes.
  • Users can open the existing text file.
  • Users can save the text file on their machine.
  • Users can print the text file via their printer.
  • Users can also copy, paste, cut, selectall text in the notepad.
  • Users can also format their text on different font-styles, font-sizes, etc

Project Prerequisites:

  • IDE Used: NetBeans 11.2 (You can use Eclipse or any other Java editor)
  • Java should be installed on the machine.
  • To build a notepad text editor using java we require basic knowledge of java and file operations.
  • Java provides by default packages such as Abstract Window Toolkit (AWT) & Swing packages to create user interface(UI) for desktop applications.

Download Notepad Java Code

Please download the source code of Java Notepad: Notepad Java Project Code

Steps to Create Notepad – Text Editor Java Project

These are the step to build Notepad Text Editor using Java:

  1. Import packages
  2. Initialize User Interface
  3. Adding Actions to buttons
  4. Performing Actions of User

1) Import packages

In this step, we will import File, AWT & Swing required packages

import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.filechooser.FileNameExtensionFilter;

2) Initialize User Interface

In this very initial step, we will create the basic user interface for our Notepad Desktop Java Application. We will create a menu such as File, Edit, Format & Sub-Menu in that such as New File, Open File, Save File, Exit, Select All Text, Cut , Copy, Paste, Change Font Family, Change Font Style, Change Font Size, etc.

Functions Definitions:

a) setLayout(layout): This function will define the layout of the frame, window, pane, in which all the components are arranged.
b) setText(“your text”): This function will set the title or the text on the label, button,etc.
c) setVisible(true): This function will make the frame or window visible to the user. By default, it is false.
d) setSize(int width, int height): This function takes two parameters such as height and width. It is used to define the size of frame/window, panel, etc.
e) add(obj): This function is used to add the components in a sequential manner to the frame or panel.
f) setAccelerator(KeyStroke keyStroke): This function sets the short-cuts keyboard for the respective menu item.
g) setSelectionMode(MODE): This function sets the selection mode of the list, it can be single or multiple.
h) setFont(Font): This function sets the font family, font style, font size of the textarea and textfield.
i) setLineWrap(true): This function sets the line-wrapping policy of the text area. By default, it is false.
j) setWrapStyleWord(true): This function sets the word-wrapping policy of the text area. By default, it is false.

Code:

public void initUI() {
    detailsOfFile = new JLabel();

    bottomPanel = new JPanel();

    //Creating Menubar
    menuBar = new JMenuBar();

    //Creating Menu "File"
    file = new JMenu("File");

    //Creating MenuItem "New"
    newdoc = new JMenuItem("New");

    //Assigning shortcut "Ctrl + N" for "New" Menu Item
    newdoc.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));

    //Creating MenuItem "Open" in notepad
    open = new JMenuItem("Open");

    //Assigning shortcut "Ctrl + O" for "Open" Menu Item
    open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));

    //Creating MenuItem "Save"
    save = new JMenuItem("Save");

    //Assigning shortcut "Ctrl + S" for "Save" Menu Item
    save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));

    //Creating MenuItem "Print" in text editor
    print = new JMenuItem("Print");

    //Assigning shortcut "Ctrl + P" for "Print" Menu Item
    print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));

    //Creating MenuItem "Exit"
    exit = new JMenuItem("Exit");

    //Assigning shortcut "ESC" for "Exit" Menu Item
    exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0));

    //Creating Menu "Edit" in Notepad
    edit = new JMenu("Edit");

    //Creating MenuItem "Copy" in java notepad
    copy = new JMenuItem("Copy");

    //Assigning shortcut "Ctrl + C" for "Copy" Menu Item
    copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));

    //Creating MenuItem "Paste" in Java Notepad
    paste = new JMenuItem("Paste");

    //Assigning shortcut "Ctrl + V" for "Paste" Menu Item
    paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));

    //Creating MenuItem "Cut"
    cut = new JMenuItem("Cut");

    //Assigning shortcut "Ctrl + X" for "Cut" Menu Item
    cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));

    //Creating MenuItem "Select All"
    selectall = new JMenuItem("Select All");

    //Assigning shortcut "Ctrl + A" for "Select All" Menu Item
    selectall.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));

    //Creating Menu "Format"
    format = new JMenu("Format");

    //Creating MenuItem "Font Family"
    fontfamily = new JMenuItem("Font Family");

    //Creating MenuItem "Font Style"
    fontstyle = new JMenuItem("Font Style");

    //Creating MenuItem "Font Size" in Java Text Editor
    fontsize = new JMenuItem("Font Size");

    //Creating List of Font Family and assigning the list values
    familylist = new JList(fontFamilyvalue);

    //Creating List of Font Styles and assigning the list values
    stylelist = new JList(stylevalues);

    //Creating List of Font Size and assigning the list values
    sizelist = new JList(sizevalue);

    //Allowing user to select only one option
    familylist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    sizelist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    stylelist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    //TextArea / Editor of Notepad
    area = new JTextArea();

    //Default font will be sam_serif and default font style will be plain and default style will be 20. 
    area.setFont(new Font("SAN_SERIF", Font.PLAIN, 20));

    //Sets the line-wrapping policy of the text area
    area.setLineWrap(true);

    //Sets the word-wrapping policy of the text area
    area.setWrapStyleWord(true);

    //Creating Scrollbars around textarea
    scpane = new JScrollPane(area);

    //Creating border for scrollpane
    scpane.setBorder(BorderFactory.createEmptyBorder());

    //Adding menubar in frame
    f.setJMenuBar(menuBar);

    //Adding all menus in menubars
    menuBar.add(file);
    menuBar.add(edit);
    menuBar.add(format);

    file.add(newdoc);
    file.add(open);
    file.add(save);
    file.add(print);
    file.add(exit);

    edit.add(copy);
    edit.add(paste);
    edit.add(cut);
    edit.add(selectall);

    format.add(fontfamily);
    format.add(fontstyle);
    format.add(fontsize);

    bottomPanel.add(detailsOfFile);

    //Setting up the size of frame
    f.setSize(980, 480);

    //Setting up the layout of frame
    f.setLayout(new BorderLayout());

    //Adding panels in frame
    f.add(scpane, BorderLayout.CENTER);
    f.add(bottomPanel, BorderLayout.SOUTH);
    //Setting Frame visible to user
    f.setVisible(true);
}

3) Adding Actions to buttons:

In this step, we basically assign the actions to our buttons.

public void addActionEvents() {
        //registering action listener to buttons
        newdoc.addActionListener(this);
        save.addActionListener(this);
        print.addActionListener(this);
        exit.addActionListener(this);
        copy.addActionListener(this);
        paste.addActionListener(this);
        cut.addActionListener(this);
        selectall.addActionListener(this);
        open.addActionListener(this);
        fontfamily.addActionListener(this);
        fontsize.addActionListener(this);
        fontstyle.addActionListener(this);

    }

4) Performing Actions of User:

In this step, we will specify what will happen when a particular button is clicked or any shortcut is pressed.

  • If a user clicks on the New button or presses key Ctrl +N then a new Text File will be created for the user.
  • If a user clicks on the Open button or presses key Ctrl +O it will open the existing user selected file using java notepad application.
  • If a user clicks on the Save button or presses Ctrl +S it will allow the user to save the file on their machine.
  • If a user clicks on the Print button or presses Ctrl + P it will allow the user to print the file on their machine.
  • If a user clicks on the Exit button or presses ESC it will close the notepad application.
  • If a user clicks on the Copy button or presses Ctrl + C it will allow the user to copy text from the editor.
  • If a user clicks on the Paste button or presses Ctrl + V it will allow the user to paste text from the java text editor.
  • If a user clicks on the Cut button or presses Ctrl + X it will allow the user to cut that text from the editor.
  • If a user clicks on the Select All button or presses Ctrl + A it will allow the user to select all text from the java text editor.
  • If a user clicks on the Font Family button it will allow the user to format the font family of the text.
  • If a user clicks on the Font Style button it will allow the user to format the font style of the text.
  • If a user clicks on the Font Size button it will allow the user to format the font size of the text.
  • If a user types any text on the editor, using keylistener we calculate the length of the text and line count of the text in the notepad.

Function Definitions:

a) setText(“your text”): This function will set the text of the text area.
b) addChoosableFileFilter(filter): This function will allow specific extensions of file to be selected provided by filter.
c) read(): This function will read text from the file.
d) write(): This function will write text to the file in notepad.
e) dispose(): This function will destroy / close the frame / window.
f) print(): This function will open the printer dialog box for printing the file in java notepad application.
g) getSelectedText(): This function will get the selected text from the user.
h) selectAll(): This function will select all the text from the text area in java notepad application.
i) getSelectionStart(): This function will return the start position of the text.
j) getSelectionEnd(): This function will return the last position of the text.
k) replaceRange(“text”, startPosition, lastPosition): This function will replace the text between the start position of text and the last position of text. This function takes three parameters: text, start position of text and end position of text.
l) getCaretPosition(): This function will return the selected text’s start position.
m) insert(text, specifiedPosition): This function will insert the text from the specified position.
n) setFont(Font): This function sets the font family, font style, font size of the textarea and textfield.
o) length(): This function will return the length of the text of the text area or text field.
p) getLineCount(): This function will return the line count of the text of the text area or text field.

Code:

public void actionPerformed(ActionEvent ae) {
        //if new option is chosen
        if (ae.getActionCommand().equals("New")) {
            //Setting Text as empty by default
            area.setText("");
        } //if open option is chosen
        else if (ae.getActionCommand().equals("Open")) {
            //Setting current by default directory "C" folder
            JFileChooser chooser = new JFileChooser("C:/");
            chooser.setAcceptAllFileFilterUsed(false);
            //Allowing only text (.txt) files extension to open
            FileNameExtensionFilter restrict = new FileNameExtensionFilter("Only .txt files", "txt");
            chooser.addChoosableFileFilter(restrict);

            int result = chooser.showOpenDialog(f);
            if (result == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                try {
                    //Reading the file
                    FileReader reader = new FileReader(file);
                    BufferedReader br = new BufferedReader(reader);
                    area.read(br, null);
                    //Closing the file after reading
                    //Clearing the memory
                    br.close();
                    area.requestFocus();
                } catch (Exception e) {
                    System.out.print(e);
                }
            }
        } //if save option is chosen in java notepad application
        else if (ae.getActionCommand().equals("Save")) {
            final JFileChooser SaveAs = new JFileChooser();
            SaveAs.setApproveButtonText("Save");
            //Opening the dialog and asking from user where to save the file.
            int actionDialog = SaveAs.showOpenDialog(f);
            if (actionDialog != JFileChooser.APPROVE_OPTION) {
                return;
            }
            File fileName = new File(SaveAs.getSelectedFile() + ".txt");
            BufferedWriter outFile = null;
            try {
                outFile = new BufferedWriter(new FileWriter(fileName));
                area.write(outFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } //if print option is chosen
        else if (ae.getActionCommand().equals("Print")) {
            try {
                //printer dialog will open
                area.print();
            } catch (Exception e) {
            }
        } //if exit option is chosen
        else if (ae.getActionCommand().equals("Exit")) {
            //Destroying/Closing the frame/window
            f.dispose();
        } //if copy option is chosen
        else if (ae.getActionCommand().equals("Copy")) {
            //Getting Selected Selected Text
            text = area.getSelectedText();
        } //if paste option is chosen
        else if (ae.getActionCommand().equals("Paste")) {
            area.insert(text, area.getCaretPosition());
        } //if cut option is chosen
        else if (ae.getActionCommand().equals("Cut")) {
            text = area.getSelectedText();
            area.replaceRange("", area.getSelectionStart(), area.getSelectionEnd());
        } //if select all option is chosen
        else if (ae.getActionCommand().equals("Select All")) {
            //Selecting all text
            area.selectAll();
        } //if font family change option is chosen in java text editor
        else if (ae.getActionCommand().equals("Font Family")) {
            //Setting up Font Family
            JOptionPane.showConfirmDialog(null, fontFamilyList, "Choose Font Family", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
            fontFamily = String.valueOf(fontFamilyList.getSelectedValue());
            newFont = new Font(fontFamily, fstyle, fsize);
            area.setFont(newFont);

        } //if font style change option is chosen
        else if (ae.getActionCommand().equals("Font Style")) {
            //Setting up Font Style
            JOptionPane.showConfirmDialog(null, fontStyleList, "Choose Font Style", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
            fstyle = stylevalue[fontStyleList.getSelectedIndex()];
            newFont = new Font(fontFamily, fstyle, fsize);
            area.setFont(newFont);

        } //if font size change option is chosen
        else if (ae.getActionCommand().equals("Font Size")) {
            //Setting up Font Size
            JOptionPane.showConfirmDialog(null, fontSizeList, "Choose Font Size", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
            fontSize = String.valueOf(fontSizeList.getSelectedValue());
            fsize = Integer.parseInt(fontSize);
            newFont = new Font(fontFamily, fstyle, fsize);
            area.setFont(newFont);

        }
    }

 public void keyTyped(KeyEvent ke) {
        //Calculating length and count of words
        cl = area.getText().length();
        linecount = area.getLineCount();
        detailsOfFile.setText("Length: " + cl + " Line: " + linecount);
    }

Java Notepad / Text Editor Output

java notepad output

Summary

Yayyy! We have finally built our Notepad – Text Editor in java. Now we can create, edit our text files on our machine: desktop / laptop.

Also, we can now important notes, to do, maintain a diary, we can also write stories, etc. From this section, we have learned how to do file operations, and how to create user interface components such as frame, panels, buttons, labels, filechooser, etc with the help of AWT and Swing packages.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

1 Response

  1. Roshani says:

    Hello sir please you can share the code Notepad ++
    Project please 🙏

Leave a Reply

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