Friday, May 9, 2014

How to create simple Notepad application - Coding


In my previous post you may get an idea to create simple GUI for our Notepad application. In this post you will see how to code on it.

ActionPerformed() method 

You may think this is very simple. But we have to think about many logical things when coding. When you are going to Save, Open and Exit you have to think about many things. First of all lets add ActionPerformed events for each and every Menu items.

There are several ways to create this events.

  • Just double click on the item( item may be a button or menu item or whatever ).
  • Right click on the relevant item in Navigator tab and follow this picture.




  • Right click on the relevant item in Design view and follow this picture.





Then you can see relevant ActionPerfomed event in source view.



You should put every code related to click on Open menu item within this OpenActionPerformed() method. But first of all I want to add codes to New(New page) menu item. This is the first menu item in File tab. Look at the following code that I put.


private void newPageActionPerformed(java.awt.event.ActionEvent evt) {                                        
        
        if(textArea.getText().isEmpty()== false){
            JDialog.setDefaultLookAndFeelDecorated(true);
            int response = JOptionPane.showConfirmDialog(null, "Do you want to save changes ?","Confirmation",JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            
            if(response == JOptionPane.NO_OPTION){
                textArea.setText("");
            }
            else if(response == JOptionPane.YES_OPTION){
                saveFileActionPerformed(evt);
                textArea.setText("");
            }
            else if(response == JOptionPane.CANCEL_OPTION){
                
            }
        }
    }     



Think about Windows Notepad. You can experiment it and get an idea what are the functions it has.
  • Think you type something without saving and then you are going to get new page.
  • What happen is, it is asking you to save or not.
  • If you choose save, save windows pop up.
  • If you choose no new page is loaded. New page load means, it clear the text area.
  • Think you didn't type anything and then you are going to get new page.
  • Then it never ask to save or something and it is already a new page here.
Now look at above code.
  • First of all it begins with if statement. It checks if the text area is empty or not. If it is not empty, it goes inside of if statement.  If it is empty, you have to do nothing because it is already like a new page.


getText() method


  • Inside the if statement you can see JDialog. This is used to create custom dialog window.
  • There is another method called setDefaultLookAndFeelDecorated(true). In oracle documentation it says, This Provides a hint as to whether or not newly created JDialogs should have their Window decorations (such as borders, widgets to close the window, title...) provided by the current look and feel. This is used as a confirmation. If you want you can skip it.
  • Then I have used JOptionPane. This is used to get popup box that allows users to do something. Mainly it has 4 methods ( showConfirmDialog(), showInputDialog(), showMessageDialog(), showOptionDialog()) to do several tasks. In this case I use showConfirmDialog() method because we need to get a confirmation. 
  • This method consist of few parameters.

showConfirmationDialog() method


showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType );


  • parentComponent - This is used to check the parent window, in our program there is only one window. It is by default a parent. So this parameter may be null. 
  • message - This is the message we asking from user.
  • title - This is the title of the window.
  • optionType - This may be, 
                            DEFAULT_OPTION 
                            YES_NO_OPTION 
                            YES_NO_CANCEL_OPTION 
                            OK_CANCEL_OPTION
  • messageType - This may be, 
                            ERROR_MESSAGE
                            INFORMATION_MESSAGE 
                            WARNING_MESSAGE 
                            QUESTION_MESSAGE
                            PLAIN_MESSAGE

You can easily understand about that method with parameters. Then we get the response from that method and we use if statement to check user's answer.

  • If answer is NO - It means you need not to save
  • If answer is YES - It means you need to save it
  • If answer is CANCEL - It means you want to exit from this dialogbox.

setText() method

  • This method is used to set the text that you want.
  • Within brackets you can type String.
  • In this program we need to clear the textArea. Because if you don't need to save existing document, and you want to get a new document, then what we can do is clear the textArea. 
  • This can be done by setText("").

If you want to save ?

  • If you select Yes from dialog, it means you want to save this file.
  • In our program we have a menuItem called Save to use to save a file. But still I didn't create that method. 
  • Go to design view and create ActionPerformed() method for save menuItem ( If you have already done this, go to next step to call this method )
  • Then you can directly call this method. 
  • After that you need to clear the textArea. Because after saving there should be a new page.
I think now you have a brief idea about, how to create ActionPerformed events. Then following code is for Exit menuItem. 




This is very simple and same as above method. Try to understand yourself.

private void exitFileActionPerformed(java.awt.event.ActionEvent evt) {                                         
        
        if(textArea.getText().isEmpty() == false){
            JDialog.setDefaultLookAndFeelDecorated(true);
            int response = JOptionPane.showConfirmDialog(null, "Do you want to save changes ?","Confirmation",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

            if(response == JOptionPane.NO_OPTION){
                System.exit(0);
            }
            else if(response == JOptionPane.YES_OPTION){
                saveFileActionPerformed(evt);
            }
        }
        else{
            System.exit(0);
        }    
    }   


exit() method


  • In this method I have used something called System.exit()
  • This method is used to terminate current execution.
  • Within brackets you have to put the state of the method.(0)
Then again you have think about closing action in JFrame.



We have to do something in here. Because if you click close button, it should be asked to save the file. Do to that we have to create event for JFrame. Follow following steps.


  • Go to Navigator in Design view and right click on JFrame and click on Properties
  • Then select Properties tab and set defaultCloseOperation to DO_NOTHING.



  • Then go to the Events tab on that window and then select WindowClosing event and create your own method and click Enter to perform actions when click Close button on JFrame.
 


  • Then go to source view and you can see the method that you have created just now. Then add following code.

private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   
        
        if(textArea.getText().isEmpty() == false){
            JDialog.setDefaultLookAndFeelDecorated(true);
            int response = JOptionPane.showConfirmDialog(null, "Do you want to save changes ?","My Notepad",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

            if(response == JOptionPane.NO_OPTION){
                System.exit(0);
            }
            else if(response == JOptionPane.YES_OPTION){
            }    
        }
        else{
            System.exit(0);
        }   
    }


  • This is very simple to understand like above methods. Everything are explained.

Open a file


So now lets look up how to use Open command in this Notepad. In this program I use JFileChooser to choose file types that I want to load into the textArea. First of all look at following code to get understand about it. 


private void openFileActionPerformed(java.awt.event.ActionEvent evt) {                                         
        
        if(textArea.getText().isEmpty() == true ){
            
            try{
                JFileChooser fileChooser = new JFileChooser("user");
                fileChooser.setFileSelectionMode(FILES_ONLY);
                fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("txt", "txt"));
                fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("java", "java"));
                fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("c", "c"));
                fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("cpp", "cpp"));
                fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("php", "php"));
                fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("html", "html"));
                fileChooser.setAcceptAllFileFilterUsed(true);

                int re = fileChooser.showOpenDialog(this);

                if(re == JFileChooser.APPROVE_OPTION){
                    File openFile = fileChooser.getSelectedFile();
                    FileReader fr = new FileReader(openFile);
                    BufferedReader br = new BufferedReader(fr);

                    textArea.read(br, null);
                    oldText = textArea.getText();
                    br.close();
                }
            }catch(Exception e){

            } 
        }
        else{
            JDialog.setDefaultLookAndFeelDecorated(true);
            int response = JOptionPane.showConfirmDialog(null, "Do you want to save changes ?","Confirmation",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

            if(response == JOptionPane.NO_OPTION){
                textArea.setText("");
                openFileActionPerformed(evt);
            }
            else if(response == JOptionPane.YES_OPTION){
                saveFileActionPerformed(evt);
                textArea.setText("");
                openFileActionPerformed(evt);
            }
        }     
    }                


This is the action code of Open file on Menu. In my last post I have noted how to get action event code for element. 

In this code you can see at first I have checked if the textArea is empty or not. If it is not empty you can go inside of the if statement. 

I think it is better to give you the project file. Download it and see what is happening. Enjoy coding :)