Simple Editor in Java
Submitted by mehfuza on Wednesday, September 11, 2013 - 21:03.
Introduction
This simple editor has only one menu with New, Open, Save, Exit option. It requires JMenuBar, JMenu, JMenuItem, ActionListener, File related classes. This tutorial demonstrate creation of menu and reading and writing the files. Once user clicks on open menu then Open dialog box is displayed and File is displayed in the display area. This simple editor can be created easily with following steps. File reading and writing part is similar to previous tutorial.Implementation
Step 1: Designing the Menu The class is application so it extends JFrame. The constructor of the class contain the code for designing the menu and adding action listeners. We require to create menu by using JMenu which include different JMenuItem like Open, Save, New, Exit. JTextArea is used for editing and displaying the text.It is created to hold and display 15 lines and 80 characters per line. Short cut key for any action can set using setMnemonic( ) function. Menu Items are created with JMenuItem class follows.- fileMenu.setMnemonic( 'F' ); // short cut key Alt + F
- saveItem.setMnemonic( 'S' );
- openItem.setMnemonic( 'O' );
- newItem.setMnemonic( 'N' );
- exitItem.setMnemonic( 'Q' );
- int result=fileChooser.showSaveDialog(MenuDemo.this);
- {
- try{
- ostream.write(area.getText());
- ostream.close();
- }
- ioe.printStackTrace();
- }
- }
- }
- });
- {
- int result=fileChooser.showOpenDialog(MenuDemo.this);
- {
- try{
- while(line!=null)
- {
- area.append(line + "\n");
- line=inStream.readLine();
- }
- inStream.close();
- }
- fe.printStackTrace();
- }
- ie.printStackTrace();
- }
- }
- }
- {
- area.setText("");
- }
- });
- }
- });
- });
Step 4: Defining the main() method
In the main method object of above class is created and some properties are set.
- {
- Editor simpleEditor=new Editor();
- simpleEditor.setDefaultCloseOperation(EXIT_ON_CLOSE);
- }
Add new comment
- 20 views