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

This is the second part of the A Simple Notepad Application tutorial. In this article you will see, how all the functions of the text editor are implemented. So, we continue our work on the text editor. We have the graphical user interface. First step to implement the functionality is to add shortcut keys to every menu item. We will ise for this KeyAdapter. When you will press any of the common shortcut keys, programm will generate the click event for corresponding button
  1. textArea.addKeyListener(new KeyAdapter(){
  2.                                 public void keyPressed(KeyEvent e){
  3.                                         if(e.getKeyCode()==KeyEvent.VK_O&&e.isControlDown())
  4.                                                 open.doClick();
  5.                                         if(e.getKeyCode()==KeyEvent.VK_S&&e.isControlDown())
  6.                                                 save.doClick();
  7.                                         if(e.getKeyCode()==KeyEvent.VK_S&&e.isControlDown()&& e.isAltDown())
  8.                                                 save_as.doClick();
  9.                                         if(e.getKeyCode()==KeyEvent.VK_F&&e.isControlDown())
  10.                                                 find.doClick();
  11.                                         if(e.getKeyCode()==KeyEvent.VK_R&&e.isControlDown())
  12.                                                 replace.doClick();
  13.                                 }
  14.                         });
In the first part we addedlisteners to the all menu items. When our class implements ActionListener interface you'll need to override public void actionPerformed(ActionEvent e) method. From the event object  e you can get the source of the event. That's why the structure of the actionPerformed method is like this
  1.  if(e.getSource() == object1){
  2. //handling object1 pressed event
  3. }
  4.  if(e.getSource() == object2){
  5. //handling object2 pressed event
  6. }
  1. Open a file.
    We will open only .txt files. That's why we use the FileNameExtensionFilter
    1. if(e.getSource() == open){
    2.         JFileChooser openFile = new JFileChooser();//object of dialog
    3.         FileNameExtensionFilter filter = new FileNameExtensionFilter("Text files", "txt");
    4.         openFile.setFileFilter(filter);//set .txt filter to dialog
    5.         if(openFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
    6.                                         openFile(openFile.getSelectedFile(),openFile.getSelectedFile().getName());                      }
    open So, if you pressed "Open File" from menu or pressed "ctrl+o" an open file dialog will appear and you will be able to choose a file. After this, openFile method will load the file into text area The work of openFile is described here:
    1. public void openFile(File openFile,String fullPath){
    2. textArea.setText("");//text area is empty
    3. filePath = fullPath;//path of file
    4. CurrentFile = openFile;
    5. String scan;
    6. FileReader file;//object to read data from file
    7. try {
    8.         file = new FileReader(openFile);
    9.         BufferedReader br = new BufferedReader(file);
    10.         while((scan = br.readLine()) != null)
    11.                 textArea.append(scan + "\n");
    12.         br.close();
    13. } catch (FileNotFoundException e1) {
    14.      JOptionPane.showMessageDialog(null,"can\'t open file!!!","ERROR",JOptionPane.ERROR_MESSAGE);
    15. } catch (IOException e1) {
    16.      JOptionPane.showMessageDialog(null,"can\'t open file!!!","ERROR",JOptionPane.ERROR_MESSAGE);      
    17. }
    18. setTitle(filePath+" Cool Reader v1.0");
    19. }              
    20. }
    Every line of the text file is appended as a new line to text Area. Reading data from file can throw some exceptions. That's why try/catch block is used.User will be informed about the error and he will be able to continue the work. In the end of work we set the name of file as the title of frame.
  2. Now, let's take a look on the "save" and "save as" options.
    1. if(e.getSource() == save &&CurrentFile!=null ){
    2.         saveFile(CurrentFile);
    3. }
    If you press "save" the saveFile method is called for the current file. If you call "save as" option, you will be asked to choose the place where file will be saved and the name of the file:
    1. if(e.getSource() == save_as){
    2.         JFileChooser saveFile = new JFileChooser();
    3.         FileNameExtensionFilter filter = new FileNameExtensionFilter("Text files", "txt");
    4.         saveFile.setFileFilter(filter);
    5.         if(saveFile.showSaveDialog(null) == JFileChooser.APPROVE_OPTION)     {
    6.                 CurrentFile = saveFile.getSelectedFile();
    7.                 saveFile(CurrentFile);
    8.         }
    9. }
    save As you see, the process of creating open file dialog and save file dialog is very similar. The save function code is next:
    1. private void saveFile(File f){
    2.         try {
    3.                 if(!f.toString().endsWith(".txt"))
    4.                         f = new File(f.toString()+".txt");
    5.                 FileWriter fw = new FileWriter(f);
    6.                 textArea.write(fw);    
    7.                 } catch (IOException e) {
    8.         JOptionPane.showMessageDialog(null,"can\'t save file!!!","ERROR",JOptionPane.ERROR_MESSAGE);
    9.                         }
    10.                 }
    First of all, this code makes a check, if the file is saved in txt format. If you don't enter the ".txt" extension, a new text file will be created. Next step is to write all the data from text area to file JTextArea write method.
  3. Now, I'll show you an example of using confirmation dialog in the program. When user will press exit menu item, a confirmation dialog will be showed thank's to this code:
    1. if(e.getSource()==exit){
    2.         int choise = JOptionPane.showConfirmDialog(null, "Do you want to save file on exit?");
    3.         if(choise==JOptionPane.NO_OPTION)
    4.                 dispose();
    5.         else
    6.                 if(choise==JOptionPane.YES_OPTION){
    7.                         save_as.doClick();
    8.                         dispose();
    9.                 }      
    exit In this case user asked, if he wants to save file. If it's no need to save a file - application is closed with dispose() method. In case of "Yes" answer, save_as item from menu is automatically clicked using doClick() method
  4. Handling the events from the popup menu is very simple thanks to build-in methods of JTextArea. The implementation of cut,copy,paste and delete options looks in the next way:
    1. //---------------POPUPMENU HANDLERS-------------------------------------
    2. if(e.getSource()==mCut||e.getSource()==cut){
    3.         textArea.cut();
    4. }
    5. if(e.getSource() == mCopy||e.getSource()==copy){
    6.         textArea.copy();
    7. }
    8. if(e.getSource() == mPaste||e.getSource()==paste){
    9.         textArea.paste();
    10. }
    11. if(e.getSource() == mDelete||e.getSource()==delete){                            textArea.setText(textArea.getText().replace(textArea.getSelectedText(),""));
    12. }
    To show the popup menu we need to listen for the mouse events. That's why in the class the MouseListener interface is implemented. From this interface we will implement only 1 method :
    1. public void mouseClicked(MouseEvent e) {
    2.         if(e.getButton()==3){
    3.                 mouseMenu.show(e.getComponent(), e.getX(), e.getY());
    4.         }      
    5. }
    This will show popup menun, when you right-click (it's 3 button on mouse) on text Area.
  5. Another type of used dialog in this aplication is message dialog. An Example of the message dialog is:
    1. if(e.getSource()==help){
    2.         JOptionPane.showMessageDialog(null, "Shortcut Keys:\nctrl + o - open file\n" +
    3.         "ctrl+s - save file\n" +
    4.         "ctrl+alt+s - save file as\n" +
    5.         "ctrl+f - find\n" +
    6.         "ctrl+r - replace","Help", JOptionPane.PLAIN_MESSAGE);
    7. }
    help So, when you use a message dialog you have to write the message, the title of the dialog and the type of the message(JOptionPane.PLAIN_MESSAGE). There are several types of messages, like error or informational message.
  6. Also, you can show a essage dialog of the specified construction. You can construct you own dialog message, for example, to ask user to input data. This is an example of creating your own dialog:
    1. if(e.getSource()==replace){
    2.         JTextField searchWord = new JTextField();
    3.         JTextField replaceWord = new JTextField();
    4.         JComponent[] replaceField = new JComponent[]{new JLabel("Find"),searchWord,new JLabel("Replace with"),replaceWord};
    5.         JOptionPane.showMessageDialog(null, replaceField,"Replace",JOptionPane.PLAIN_MESSAGE);
    6.         String findString = searchWord.getText();
    7.         String replaceString = replaceWord.getText();
    8.         textArea.setText(textArea.getText().replaceAll(findString, replaceString));
    9. }
The result If you check the attached project, you'll see that the full application is build using components, described in the article. So, if you know these basic components, you can write a variety of code for different purposes.

Add new comment