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){
            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){
            else if(response == JOptionPane.YES_OPTION){
            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, 
  • messageType - This may be, 

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){
            int response = JOptionPane.showConfirmDialog(null, "Do you want to save changes ?","Confirmation",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

            if(response == JOptionPane.NO_OPTION){
            else if(response == JOptionPane.YES_OPTION){

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){
            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){
            else if(response == JOptionPane.YES_OPTION){

  • 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 ){
                JFileChooser fileChooser = new JFileChooser("user");
                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"));

                int re = fileChooser.showOpenDialog(this);

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

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

            int response = JOptionPane.showConfirmDialog(null, "Do you want to save changes ?","Confirmation",JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

            if(response == JOptionPane.NO_OPTION){
            else if(response == JOptionPane.YES_OPTION){

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 :)

Tuesday, May 6, 2014

How to create simple Notepad application - Create GUI

This is the first post of GUI application developing in this blog. However we almost covered big theories but we need to understand how to use these theories in practical programs. In this post I am going to create the GUI for Simple Notepad Application. I cannot complete this whole app in one blog post, so this is the beginning of a series of posts.

How to begin a Project ?

I know you  are very familiar with Windows Notepad application. This is very simple, fast and less GUI modifications. And it has no any connection with databases. So we need not to worry about databases. But If you are going to create Enterprise Java Application, first of all you need to think about databases and create them. Then you can think about the GUI of the application. But in this application there is no database so, we can create GUI.

How to create a GUI using NetBeans ?

In this post I note you how to create GUI for Notepad application using NetBeans. I am using Netbeans IDE 8.0 version.

How to create a new Project

  • Go to File then click on New Project. ( or CTRL+SHIFT+N )

  • Then select Java in Categories and then select Java Application in projects and click next.
  • Then type your project name and remove the tick on Create Main class and then click Finish.

  • Then you can see the project that you have created in Projects tab. ( If you cannot see this tab, go to Window on menu and then click on Projects or CTRL+1 )

How to create a new Package

  • Now we have to think about Package for our application. 
  • You can see Source Packages under your project.
  • Right click on New -> Java package. Then you can type a Package name and click Finish.

  • Then you will able to see the package that you have created under Source Packages.

How to create a JFrame

  • Lets move on JFrame now. This is the main frame that we create our application.
  • Right click on your Package and then click on New and then click on JFrame Form.

  • Then you can type a class name for JFrame and click Finish.

  • Now you will be able to see following window. This is called Design view of your project. For coding, you have to move to the Source view.

How to add elements  into JFrame

  • Now we need to add element one by one. Use following steps.
    1. Add JScrollPane
    2. Add MenuBar
    3. Add TextArea

  • In the right side of design view, you can see Palette window. In this window, there are Swing Containers, Swing Controls, Swing Windows, Swing Menus, Swing Filters, AWT...etc. 

  • You can drag and drop any element into your JFrame.
  • First I need to add JScrollPane. You can see this in Swing Containers section as Scroll Pane. Then you can drag and drop into your JFrame.
  • Then resize it to fix with JFrame( Scroll Pane size = JFrame size ).
  • In right-hand side you can see something called Navigator. In this tab you can see each and every elements that you have dropped into JFrame. You can navigate through them.

  • If you want to rename any element, you can do it now on Navigator tab. I renamed my jScrollPane1 to scroll ( Or right click on the element and select Change variable name ). 

  • According to above steps, you can add Menu bar from Swing Menus and then add Text Area from Swing controls.

How to change Menu bar items

  • In this step I am gonna add Menu bar items. First of all it is better if you can go to default Notepad application in Windows to understand about Menu bar and Menu items.

  • In my program I am going to add few of these Menu items for my application. 
  • Your default menu bar has only two JMenus( File and Edit ).

  • Right click on the File -> Add from Palette -> Menu item.

  • Likewise add all elements into your notepad application. Look at the following pictures. This is what I am going to create.

  • Then you can change its appeared name and variable name as you wish. But may be very understandable if you can use following variable names to each item.
      • Scroll Pane - scrollPane
      • Menu Bar - menuBar
      • File Menu - file
      • Edit Menu - edit
      • Help Menu - help
      • New Menu Item - newPage
      • Open Menu Item - openFile
      • Save Menu Item - saveFile
      • Exit Menu Item - exitFile
      • Copy Menu Item - copy
      • Cut Menu Item - cut
      • Paste Menu Item - paste
      • Delete Menu Item - delete
      • Select all Menu Item - selectAll
      • Version Menu Item - version
      • About Menu Item - about
      • Contact us Menu Item - contact
      • Text Area - textArea
Final Navigator should be like this.

How to add key shortcuts to JMenu Items

  • You know about Windows key short-cuts. ( CTRL + c for copy, CTRL + v for paste and so on. ).
  • We have to add them to our application also.
  • It is very simple with NetBeans. Just you have to select relevant Menu item.
  • Click on shortcut.

  • Type the Key Stroke ( You can follow common shortcut keys. More details ).

  • Then select CTRL, ALT or SHIFT then click ok.
Now your final GUI should be like this. In next post lets move with coding.

Here is the Coding part