Introduction to javax.swing Library. A Simple Notepad Application. Part 1

In this article I'll describe how to create a simple Notepad application using javax.swing library. Now, you know how to create java projects in Eclipse. So, we will create a new project, called coolReader. First of all, I'll show you the structure of the project: structure So, the project consists of 3 classes and a set of images, used to create some buttons. Now,we wil speak about coolReader class. This class is the class, that has the full implementation of the GUI and event handling. Let's look on the class definition:
  1. public class coolReader extends JFrame implements ActionListener,MouseListener,ListSelectionListener
coolReader class extends JFrame class and implements a list of interfaces - ActionListener for handling events from buttons,MouseListener to handle mouse event and ListSelectionListener for events, generated by selection lists. The next step of work it's to define elements, that we will use in GUI. You can define all the components as fields in this way:
  1. private JTextArea       textArea;
  2. private JMenuBar        readerBar;
  3. private JMenu           textMenu,
  4.                         editMenu,
  5.                         formatMenu,
  6.                         aboutMenu,
  7.                         fontSubMenu,
  8.                         sizeSubMenu;
  9. private JMenuItem       open,
  10.                         save,
  11.                         save_as,
  12.                         exit,
  13.                         cut,
  14.                         copy,
  15.                         paste,
  16.                         delete,
  17.                         find,
  18.                         replace,
  19.                         help,
  20.                         about;
  21. private JPopupMenu      mouseMenu;
  22. private JMenuItem       mCut,
  23.                         mCopy,
  24.                         mPaste,
  25.                         mDelete;
  26. private JList<String>   fontSizeList,  
  27.                         fontList;
  28. private JToggleButton   italicBtn,
  29.                         boldBtn;
  30. private String          filePath;
  31. private JScrollPane     textPanel,
  32.                         catalogPanel;
  33. private File            CurrentFile;
  34. private int             fontStyle;
  35. private int             currentFontSize;
  36. private String          currentFont;
  37. private JTree           catalog;
  38. private Container   editorFrame;
  39. ////------------------------------
  40. private FileSystemModel fileSystemModel;
  41. //---------------------------------
Don't be afraid of huge number of fields. All of them have descriptive names and we will about them during the construction of the editor's frame. Now, all the fields must be initialized and added to the frame. We will do it in the constructor of the coolReader class. The first step, it's to initialize the main component of text editor - text area:
  1. textArea = new JTextArea(); //initilize text area
  2. textArea.setBounds(0,50,860,640);//set size of text area
  3. textArea.setAutoscrolls(true);//it possible to scroll text area
  4. textArea.addMouseListener(this);//adding mouseListener to handle events
  5. textPanel = new JScrollPane(textArea);//add text area to scroll component
The next lines of code create a File System Panel in the left part of the frame. We will speak about it latter, because it's not related to the GUI and swing library.
  1. fileSystemModel = new FileSystemModel(new File("c:\\"));
  2. catalog = new JTree(fileSystemModel);//class to present trees in java
  3. catalog.setAutoscrolls(true);//set Jtree autoscroll
  4. //add event listener using anonymous class
  5. //open's a file only if it's extension is .txt
  6. catalog.addTreeSelectionListener(new TreeSelectionListener() {
  7.                               public void valueChanged(TreeSelectionEvent event) {
  8.                                File file = (File) catalog.getLastSelectedPathComponent();
  9.                                System.out.println(file.getAbsolutePath().substring(file.getAbsolutePath().length()-3));
  10.                                if(file.getAbsolutePath().substring(file.getAbsolutePath().length()-3).equals("txt")){
  11.                                    openFile(file,file.getAbsolutePath());
  12.                                }
  13.                               }
  14.                             });
  15. catalogPanel = new JScrollPane(catalog);//a scroll panel that will hold file system tree
Now we need to handle resize event of the frame. For this, a component adapter is used:
  1. this.addComponentListener(new ComponentAdapter(){
  2.                                 public void componentResized(ComponentEvent e){
  3.                 catalog.setSize(e.getComponent().getSize().width/5, e.getComponent().getSize().height);
  4.                                         repaint();
  5.                                 }
  6.                         });
After this, we can finish the building of the frame. As you can see, editor consists of 3 parts : Menu, File System Explorer and Text area. Now we will add File System Explorer and text Area using Border Layout:
  1. editorFrame = this.getContentPane();
  2. editorFrame.setLayout(new BorderLayout());
  3. catalogPanel.setPreferredSize(new Dimension(getBounds().width/5,10));
  4. editorFrame.add(catalogPanel,BorderLayout.LINE_START);
  5. ditorFrame.add(textPanel);
Every editor has a popup menu, that you can see, when you right-click text area. We will create the same thing with this code:
  1. mouseMenu = new JPopupMenu(); //iitialize popup menu
  2. //initializing menu items and adding actionListener for every item                     
  3. mCut = new JMenuItem("Cut");
  4. mCut.addActionListener(this);
  5. mCopy = new JMenuItem("Copy");
  6. mCopy.addActionListener(this);
  7. mPaste = new JMenuItem("Paste");
  8. mPaste.addActionListener(this);
  9. mDelete = new JMenuItem("Delete");
  10. mDelete.addActionListener(this);
  11. //add Items to menu            
  12. mouseMenu.add(mCut);
  13. mouseMenu.add(mCopy);
  14. mouseMenu.add(mPaste);
  15. mouseMenu.add(mDelete);
The popup menu will look like this: popup menu Let's create a simple menu in the top of frame:
  1. readerBar = new JMenuBar();
I used some set of images for this menu, so now we will load all the images to use them in the process of menu's building:
  1. ImageIcon openIcon = new ImageIcon(getClass().getResource("images/open.png"));
  2. ImageIcon saveIcon = new ImageIcon(getClass().getResource("images/save.png"));
  3. ImageIcon exitIcon = new ImageIcon(getClass().getResource("images/exit.png"));
  4. ImageIcon cutIcon = new ImageIcon(getClass().getResource("images/cut.png"));
  5. ImageIcon copyIcon = new ImageIcon(getClass().getResource("images/copy.png"));
  6. ImageIcon pasteIcon = new ImageIcon(getClass().getResource("images/paste.png"));
  7. ImageIcon deleteIcon = new ImageIcon(getClass().getResource("images/delete.png"));
  8. ImageIcon findIcon = new ImageIcon(getClass().getResource("images/find.png"));
  9. ImageIcon replaceIcon = new ImageIcon(getClass().getResource("images/replace.png"));
  10. ImageIcon helpIcon = new ImageIcon(getClass().getResource("images/help.png"));
  11. ImageIcon aboutIcon = new ImageIcon(getClass().getResource("images/about.png"));
The process of creating menu is very simple. I'll describe only menu "File" and the other menus are created in the similar way. The common steps are :
  1. create JMenu name of menu
  2. create a JMenuItem with specified icon and description
  3. add actionListener for menu item
  4. add MenuItem objects to JMenu object
  5. add JMenu to JMenuBar
Example of File Menu:
  1. textMenu = new JMenu("File");
  2. open = new JMenuItem("Open",openIcon); 
  3. open.addActionListener(this);
  4. save = new JMenuItem("Save",saveIcon);
  5. save.addActionListener(this);
  6.                        
  7. save_as = new JMenuItem("Save as",saveIcon);
  8. save_as.addActionListener(this);
  9.                        
  10. exit = new JMenuItem("Exit",exitIcon);
  11. exit.addActionListener(this);
  12.                        
  13. textMenu.add(open);
  14. textMenu.addSeparator();
  15. textMenu.add(save);
  16. textMenu.add(save_as);
  17. textMenu.addSeparator();
  18. textMenu.add(exit);
  19. readerBar.add(textMenu);
  20. setJMenuBar(readerBar);        
The last step to create GUI is to set title to the frame and the default operation on close. It can be done in the following way:
  1. setTitle("Cool Editor v1.0");
  2. setDefaultCloseOperation(EXIT_ON_CLOSE);
To test the frame lets create the main class.
  1. import java.awt.Dimension;
  2.  
  3.  
  4. public class main {
  5.  
  6.         /**
  7.          * @param args
  8.          */
  9.         public static void main(String[] args) {
  10.                 // TODO Auto-generated method stub
  11.                 coolReader myEditor = new coolReader();
  12.                 myEditor.setSize(new Dimension(640,480));
  13.                 myEditor.setVisible(true);
  14.         }
  15.  
  16. }
Here we create a coolReader object, set it's size and make it to be visible. Now, our frame editor looks like this: Notepad It's only the frame, but no any functionality is realized. We will speak about the realization of all functions in the next article.

Add new comment