Thursday, April 18, 2013

Text Editor program

The Text Editor program is simple but it is able to edit text, allow you to choose a file for opening and saving, read text from a file, and write text to the file. In the Text Editor program, you will learn how to create graphic user interface (GUI) program, to read, and to write data file.  The program has a main interface window (frame). On the frame window, we have an internal frame that you can drag and drop. On the internal frame, there are three buttons and one textarea. The first button is to perform New command; The second performs Open command and the third performs Save command. The textarea allows you to display the text from the file and edit the text.

TextEditor source code:

1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4 import javax.swing.event.*;
5 import java.awt.image.*;
6 import javax.swing.filechooser.*;
7 import java.io.*;
8 class  Editor extends JFrame implements ActionListener{
            JTextArea txtArea;
            JScrollPane scr;
            JPanel panel;
            JButton btNew;
            JButton btOpen;
            JButton btSave;
            ImageIcon icoNew;
            ImageIcon icoOpen;
            ImageIcon icoSave;
            String filen;
9          Editor(){
10                    super("Text Editor");
11                    filen="";
12                    setDefaultCloseOperation(EXIT_ON_CLOSE);
13                    setSize(830,600);
14                    setResizable(false);
15                    Container content=getContentPane();
16                    JDesktopPane des=new JDesktopPane();
17                    content.add(des, BorderLayout.CENTER);
18                    JInternalFrame f1=new JInternalFrame();
19                    f1.setSize(830,700);
20                    f1.setLocation(2,2);
21                    f1.setLayout(null);
22                    f1.setVisible(true);
23                    des.add(f1);
24                    icoNew=new ImageIcon("newIcon.gif");
25                    btNew=new JButton("",icoNew);
26                    btNew.setBounds(5,5,25,20);
27                    btNew.setToolTipText("New document");
28                    btNew.addActionListener(this);
29                    icoOpen=new ImageIcon("openIcon.png");
30                    btOpen=new JButton("",icoOpen);
31                    btOpen.setBounds(35,5,25,20);
32                    btOpen.setToolTipText("Open document");
33                    btOpen.addActionListener(this);              
34                    icoSave=new ImageIcon("saveIcon.png");
35                    btSave=new JButton("",icoSave);
36                    btSave.setBounds(65,5,20,20);
37                    btSave.setToolTipText("Save document");
38                    btSave.addActionListener(this);               
39                    f1.add(btNew);
40                    f1.add(btOpen);
41                    f1.add(btSave);
42                    txtArea = new JTextArea(30,72);
43                    txtArea.setEditable(true);
44                    scr=new JScrollPane(txtArea);
45                    panel=new JPanel();
46                    panel.setBounds(2,30,800,550);
47                    panel.add(scr,BorderLayout.SOUTH);
48                    f1.add(panel);
49                    f1.moveToFront();
50                    setVisible(true);
                       
            }
51 public void actionPerformed(ActionEvent e){
            if(e.getSource()==btOpen) showOpenDialog(this);
            else if(e.getSource()==btSave) {
                        if(filen.equals(""))
                                    showSaveFileDialog(this);
                       
                        else {saveToFile(filen,txtArea.getText());}
                        }
            else if(e.getSource()==btNew){
                        filen="";
                        txtArea.setText("");
            }
            }

52 public void readFile(String filename){
         
  try{ //catch errors if any
            String textline,content="";
            FileReader fr=new FileReader(filename);
            BufferedReader br=new BufferedReader(fr);
           while ((textline=br.readLine())!=null){
                        //Read  lines of string from the file using readLine() method
           
                       content+=textline+"\n";
             
             }         
            txtArea.setText(content);
            br.close();//close file using close() method
            fr.close();    
     } catch(Exception ie){System.out.println("IO problem!");ie.printStackTrace();}

  }


53 public static void saveToFile(String filename,String text){
   try{ //catch errors if any
    FileWriter fw=new FileWriter(filename); 
     BufferedWriter bw=new BufferedWriter(fw);
     bw.write(text);
     bw.flush();
     bw.close();  
    }catch(IOException ie){System.out.println("Error in writing to file...");}      
}


54 public void showOpenDialog(Frame frame){
    JFileChooser chooser = new JFileChooser();   
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Text File", "txt");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(frame);
    if(returnVal == JFileChooser.APPROVE_OPTION) { 
            filen=chooser.getSelectedFile().toString();   
            readFile(filen);
                       
           
         }
 }

55 public void showSaveFileDialog(Frame frame){
         JFileChooser chooser = new JFileChooser();   
          FileNameExtensionFilter filter = new FileNameExtensionFilter("Text File", "txt");
          chooser.setFileFilter(filter);
          int returnVal = chooser.showSaveDialog(frame);
          if(returnVal == JFileChooser.APPROVE_OPTION) { 
                   filen=chooser.getSelectedFile().toString();
                   saveToFile(filen,txtArea.getText());
           
           
         }
 }

}

56 public class TextEditor{
  
      public static void main(String args[]){
           new Editor();
  
}


}
Text Editor program in Java

Code Explanation:
1-7 include classes needed to get frame, controls, to draw interface and reponse to actions, display file dialog, and read and write file.
8 The Editor class extends the  JFrame class and implements the ActionListener interface. The JFrame class allows you to display a frame window that is the main interface of the program. The ActionListener interface contains actionPerformed method to be implemented to perform the action when a button is clicked. 
9 It is the constructor of the Editor class. The code in the constructor is executed to initialize the program interface.
10 Diplay "Text Editor" on the top bar of the frame window.
11 Initialize the image file name. When the program first loads, the file name is set to empty string.
12 Allow the frame window to close when the close button on the frame is clicked.
13 The frame window displays 830 pixels wide, and 700 pixels high.
14 The frame window is not allowed to resize.
15 Controls or components can be drawn on the frame window are tracked by frame container.
16 Create JDesktopPane des object to contain the internal frame.
17 Add the des object to the main frame window.
18 Create an internal frame f1 object.  
19 Set the internal frame f1 size.
20 Define the location (left, top) of the internal frame f1.
21 Set the layout of the form to null so that you can customize the sizes and locations of controls to be placed on the internal frame.
22 Make the internal frame visible to the user.
23 Add the internal frame to des object.
24-41 Create three ImageIcon objcts, three button objects which hold the ImageIcon objects. Each button object has  tool tip text that is displayed when the mouse point is over it. The button can repond to the external event by registering it to the ActionListener interface.  The three buttons are added to internal frame by using its add (component) method. 
42-43 Create JTextArea txtArea object and make it editable. The txtArea object is used to display text and edit text.
44 Create a JScrollPane scr object to wrap the txtArea object. This will make the txtArea object scrollable when the txtArea space is not enough to display the text.
45 Create JPanel panel object to wrap the scr object.
46 Specify the size and location of panel object when it is displayed on the internal frame.
47 Define the location (left, top), and size (width, height) of the panel object.
48 Add src object to panel object.
49 Move the internal frame to the font of the window interface.
50 Make user the main frame window is visible to the user.
51 The actionPerformed method works when the user clicks the button. This method is in the ActionListener interface.
52 The readFile method is implemented to read text in a file that is selected by the user from file chooser dialog.
53 The saveToFile method is used to write the text in the txtArea to the file.
54 It is the code to display an open file dialog when the user clicks the Open command button. 
55 The save dialog is open when the user clicks on the Save command button to save the current text to a new file.
56 TextEditor class has the main method to start the program.

1 comment:

  1. You made some nice points there. I did a search on the matter and found mainly people will agree with your blog. Google SEO

    ReplyDelete