Programming in Java Using the MVC Architecture

Introduction

This article provides the basic concepts of the MVC framework. The MVC framework separates the data access layer, business logic code and the graphical user interface that must be defined and designed to let the user interact with the application. This application has the following three parts:

  1. Model: this part of the framework stores the data of the application, such as databases, text data, files and/or other web resources.

  2. View: this is the graphical user interface of the application. It would contain various buttons, text boxes and other controls to let the user interact with the application to complete his projects depending on the sort of the software being used.

  3. Controller: the actual back-end code constitutes the controller of the framework. A controller controls the data coming from the users, or going to the user from a model.

This sets up a condition of validation, because the stream of data (coming from or going to the user) is always validated on the controller. That is why it makes the data more consistent by removing any chance of invalid data entry or unauthorized data deletion from the application's data source.

Background of MVC

In this short section I will try to provide a basic overview of the MVC framework. This section is not for Java-specific framework, but for the MVC framework itself. Beginners might be interested in knowing what this MVC framework is, how it interacts and how it makes the software development efficient. But if you already understand the MVC framework then you don't really want to read this section, continue to the development of the application in the next section.

The MVC framework is generally a term for a software architecture for implementing the user interfaces. You can separate the software's source code into the following three layers.

  1. Model

  2. View

  3. Controller

Then you can develop them separately. This way you don't need to scratch your head once your application reaches an enterprise level and your source code looks a bit messy and cannot be debugged. In MVC you have all your three layers separate and this way you can control, develop, debug or add features to all of the layers separately.

A very good feature of the MVC framework is that is hides the data access layer from the users. That is, the data access layer or the data is never actually called directly by the user; from the interface. This way, the user must perform the actions that he is allowed to. This feature allows the developers to create groups or roles of users that are allowed to access the data; such as Admins, Guests and so on.

Another good thing about this framework is that it doesn't let the application get so complicated and all the three segments of the application interfering with each other in a single source code package. So you always understand where the problem occurred. Common examples of this would be:

  1. When you understand that the problem is in the data access layer. For example, in the database you've allowed null entries, so now spam users would be able to leave the data inconsistent and cause a problem of redundancy. You can edit the data access layer, so that you can define the columns to not have null values.

  2. When the view is not showing the data correctly, such as scenarios where the binding of the data is not accurate, or the format is not correct like the format of the date and time values. You can simply just edit the View section of your application to make it work again, instead of editing the entire page containing various variables for back-end code and/or the data access code.

  3. When the logic is not correctly defined. Sometimes the data is correct, the view is correctly bound to the resources, but the logic of your application is not correct. This type of problem is hard to analyze because the developer must think about where the code went wrong by giving it a rough try or by debugging the code using the IDE and putting a few breakpoints at the locations.

These are a few of the good points of the MVC framework for developing the software applications. In a visual representation, the MVC framework works in the following way:

mvc framework

The preceding image clarifies that the user is not able to connect to the data sources himself. Instead he must interact with the top-level layers to access the data. Such as, for the view, he interacts with buttons and the buttons then call the controller to perform an action on the data (if required). But the data is not directly accessible by the user. This makes the data source secure from potential users. Anyhow, there is always a threat of potential user.

I wrote an article about the ASP.NET MVC framework, where I demonstrated the MVC framework before digging deeper into the ASP.NET's MVC framework, just like this one. So, if you're interested in learning more for MVC framework you might be interested in reading that article one time, just the MVC section, not the ASP.NET part. You can read that article here and you can also post any queries or questions about that article on it.

Building the application

Now for the actual implementation of this framework and building over the Java-based application. In the following procedure, I will show you how you can (using this very framework) create applications starting from applications as simple as a Hello world application to as much complex as enterprise-level applications using Java.

Setting the environment: for Java beginners

For developing Java applications, you are required to have an environment set up. An environment requires an IDE for writing the source code and managing the required libraries into one single package. A few popular ones nowadays are the following:

  1. Eclipse for Java: Eclipse is a greatly used Java IDE. It supports other languages too, but since we're talking about Java applications I highlighted only Java.

  2. NetBeans by Oracle: NetBeans is an IDE developed under Oracle license and is mostly used by beginners for the sake that it helps them create a GUI by drag-and-drop feature. I am also using NetBeans for Java development, for Android development I prefer Eclipse. You can choose on your own as your taste would like.

And the Java SDK. Now it depends on which level of application you're going to developer, there are many types of Java SDKs available out there for you and you can choose from among them. I am using the Java SE SDK and it satisfies my requirements. A list of the Java SDKs available for download and popular are the following:

  1. Java SE: Standard edition. Perfect for small applications, like desktop or other applications that are not much complex.

  2. Java EE: Enterprise edition. Should be preferred over Java SE if you're going to develop an enterprise application and the program should be complex.

  3. Java ME: Micro edition. It is used to develop mobile applications, such as jar applications and other projects that are to be run over mobile devices. It should be used because it requires less memory and a small heap size for the application to run, thus suitable for mobile application programming.

  4. Then they continue to all the way to TV, Cards and so on and so forth. Learn more here.

You can download any SDK, the Java language would be similar. So the code in my article would be a good fit you in any condition. You can download and install the SDK on your machine. Once this step has been taken you can continue to the programming.

The installation of the IDE would require a JAVA_HOME system variable to be declared. That is a simple task but a bit confusing for beginners. Go to the properties of "My Computer" and inside it the Advanced system settings then Environment variables. Inside it create a new system variable and name it JAVA_HOME and the value must be the location where the bin folder is located.

system properties

Once this step is done, the IDE would automatically continue setting the required libraries and would install. You can then continue to create a new application and start making an MVC-based Java application.

Creating the application

The source code is relative to my IDE, yours might be different.

The next step is to create the application. Depending on your IDE, create a new application, a simple Java based application.

You should take care of one thing. Unlike C#, in Java your class name and the file name containing the class must match for the programs to run. If they don't then Java would complain, saying, the class must exist in its own file. So, if you want to continue with this article, you should name your application's files as I have (I will specify the names of the packages and the files along with the code they contain) or you can create your own project and then edit the names of the classes and/or packages.

When you create the application, in Eclipse it would be an empty project whereas in NetBeans it creates the entire package (with exact same name of the application) and create a class with a Main function. In my case I named the project JavaHelloCollections. If you want to follow the article, name it as it is, otherwise just follow the concept of "first package in the application". The class file in this package (depending on your IDE) would be located under the package, open it.

  1. /* 
  2.  * To change this license header, choose License Headers in Project Properties. 
  3.  * To change this template file, choose Tools | Templates 
  4.  * and open the template in the editor. 
  5.  */  
  6. package javahellocollections;  
  7.   
  8. /** 
  9.  * 
  10.  * @author AfzaalAhmad 
  11.  */  
  12.   
  13. public class JavaHelloCollections {  
  14.   
  15.     /** 
  16.      * @param args the command line arguments 
  17.      */  
  18.     public static void main(String[] args) {  
  19.         // TODO code application logic here  
  20.     }  
  21. }  

This is a very basic application that does nothing but compiles and runs. Up to this stage the application has been created but lacks the MVC pattern of programming. That stage comes after this one. So, to create the business logic of our application we're actually not going to edit this file, we're going to define the MVC pattern of our application and then we will use that pattern to ensure that the user interacts with the view. The view interacts with the controller and the controller provides the data from the model after making calls to the model.

Implementing the MVC pattern

As far as I now, we've set our environment and created the application that runs. Now to implement the MVC pattern in our application and ensure that the application follows the rules.

In Java we create packages just like we create namespaces in C#, C++ and other object-oriented programming languages. Packages allow us to make a collection of similar classes, or classes that are required in the same order or for the same cause. In our application we must create an MVC pattern. For that we can create three packages, one for Model, one for View and one for Controller. Then we can add all of our Models, Views and Controllers in these packages and use them in various packages wherever needed.

This way, we can separate all of the three sections from one another, yet we can call them in our sections by importing the packages. This way, the model would be left to be used by the controller, the view should make a call to the controller to get or update the data.

In this article, I will be using a file example to read and write the data to the file. You can use your own data source; database, web resource and so on.

We will develop the application first and then see the changes by running the application. Then there actually is no requirement to follow, to create the view first then create a controller to render the view and then to create a model to add some data. We can start by creating a section and then merge them into one single application and then run it.

Creating the Model

Let us start by creating a model for our application. This model would provide the data to our application. One thing you should consider is, that the model is not just a class to define the structure of the data in our application, like we do in the database applications. The structure must be defined there, in a simple application there is no need. This ambiguity is generally defined and created by the Entity Framework on .NET framework where you define a class for the structure of your database table and then fill in a collection of objects of that class from the database. A model is the part that contains your data. It can provide you with the data and can update the data, even the controller makes a call to the model to update itself, which means that the controller sends the data to the model and the model then updates the data on the disk.

First, create a new package. Remember to create a new package under the same project and not the same package. These would be two separate packages for the same project and we will be using them in our application where required. Name this package JavaMVCModels. Once done, create a new class file under it. This class would act as our model for the application. Name it, HelloWorldModel. Open the file and alter the file. Our scenario is:

  1. Allow the user to load the data from a data source, such as a file.

  2. Allow the user to update the data in the file.

Inside the class, write the following code:

  1. /* 
  2.  * To change this license header, choose License Headers in Project Properties. 
  3.  * To change this template file, choose Tools | Templates 
  4.  * and open the template in the editor. 
  5.  */  
  6. package JavaMVCModels;  
  7.   
  8. import java.io.*;  
  9. import java.nio.file.Files;  
  10. import java.nio.file.Paths;  
  11.   
  12. /** 
  13.  * 
  14.  * @author AfzaalAhmad 
  15.  */  
  16. public class HelloWorldModel {  
  17.     public String getData() throws FileNotFoundException, IOException {  
  18.           
  19.         if(!(new File("F:\\file.txt").isFile())) {  
  20.             // Create -- Make sure file exists -- the file before continuing  
  21.             Files.createFile(Paths.get("F:\\file.txt"));  
  22.         }  
  23.           
  24.         String data;  
  25.         // We will be using a try-with-resource block  
  26.         try (BufferedReader reader = new BufferedReader(  
  27.                 new FileReader("F:\\file.txt"))) {  
  28.             // Access the data from the file  
  29.             // Create a new StringBuilder  
  30.             StringBuilder string = new StringBuilder();  
  31.               
  32.             // Read line-by-line  
  33.             String line = reader.readLine();  
  34.             string.append("<html>");  
  35.             // While there comes a new line, execute this  
  36.             while(line != null) {  
  37.                 // Add these lines to the String builder  
  38.                 string.append(line);  
  39.                 string.append("<br />");  
  40.                 // Read the next line  
  41.                 line = reader.readLine();  
  42.             }  
  43.             string.append("</html>");  
  44.             data = string.toString();  
  45.         } catch (Exception er) {  
  46.             // Since there was an error, you probably want to notify the user  
  47.             // For that error. So return the error.  
  48.             data = er.getMessage();  
  49.         }  
  50.         // Return the string read from the file  
  51.         return data;  
  52.     }  
  53.       
  54.     public boolean writeData(String data) throws IOException, FileNotFoundException  
  55.     {  
  56.         // Save the data to the File  
  57.         try (BufferedWriter writer = new BufferedWriter(  
  58.                                         new FileWriter("F:\\file.txt"))) {  
  59.             // Write the data to the File  
  60.             writer.write(data);  
  61.             // Return indicating the data was written  
  62.             return true;  
  63.         } catch (Exception er) {  
  64.             return false;  
  65.         }  
  66.     }  
  67. }  

The preceding code can be explained in the following few stages:

  1. First of all is the declaration of the package in which this class exists. JavaMVCModels is the package that would contain the class file.

  2. The class name and the file name is similar.

  3. The class contains two methods, one to extract the data and one to save the data from the user.

The preceding code uses the File APIs of the Java language. You can find File, BufferedWriter, BufferedReader and other classes in the Java documentations and I do not need to explain them. They store data to and extract data from files.

In Java SE 7 there is the new functionality of try-with-resources blocks that automatically clean and dispose of the resources. A similar one is being used here, otherwise I would have used a finally block to manually call the .close() function. This is well described on the Java documentations.

The model doesn't need to interact with the view or the controller, instead the controller would trigger the functions of the model. That is why we're not going to write any other code, any code apart from getting/setting the data of our application. That is the exact reason I am not importing any other package in this class (apart from that Java IO API for data access), otherwise in other classes you will see that I will be making an import to other classes and packages as a whole.

Creating the view: using the NetBeans

Note: If you're using the Eclipse IDE then you can simply write the code from my View, Eclipse doesn't support drag-and-drop for the Swing GUI like NetBeans does.

Now for the View portion of the application. A similar process should be taken under consideration. A new package with the name JavaMVCViews would be created and a class for HelloWorldView would be created. But in a slightly different manner, you should create the package first. Once you've created it, create a new swing JFrame form. Fill in the details and then continue. In my case the name was HelloWorldView.

new JFrame form

NetBeans allows the developer to use a toolbox to drag-and-drop the controls over the window box and create the GUI for their applications. You can use the same and create a simple GUI that would look like the following one.

simple gui

This is our view for the application and contains enough controls for our application to work like it must. The View's work is just to display what controller has allowed it to. This view contains a few controls, that controller should be able to interact with to display them or hide them on will.

For developers, here is the code that you can write in your application to create a similar view.

  1. /* 
  2.  * To change this license header, choose License Headers in Project Properties. 
  3.  * To change this template file, choose Tools | Templates 
  4.  * and open the template in the editor. 
  5.  */  
  6. package JavaMVCViews;  
  7.   
  8. // Call the import  
  9. import JavaMVCControllers.*;  
  10.   
  11. /** 
  12.  * 
  13.  * @author AfzaalAhmad 
  14.  */  
  15. public class HelloWorldView extends javax.swing.JFrame {  
  16.     // Create the class for the Controller  
  17.     private HelloWorldController controller = new HelloWorldController();  
  18.   
  19.     /** 
  20.      * Creates new form HelloWorldView 
  21.      */  
  22.     public HelloWorldView() {  
  23.         initComponents();  
  24.     }  
  25.   
  26.     /** 
  27.      * This method is called from within the constructor to initialize the form. 
  28.      * WARNING: Do NOT modify this code. The content of this method is always 
  29.      * regenerated by the Form Editor. 
  30.      */  
  31.     @SuppressWarnings("unchecked")  
  32.     // <editor-fold defaultstate="collapsed" desc="Generated Code">                            
  33.     private void initComponents() {  
  34.   
  35.         myLabel = new javax.swing.JLabel();  
  36.         loadData = new javax.swing.JButton();  
  37.         jScrollPane1 = new javax.swing.JScrollPane();  
  38.         myMessage = new javax.swing.JTextArea();  
  39.         writeData = new javax.swing.JButton();  
  40.   
  41.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);  
  42.         setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));  
  43.         setName("myFrame"); // NOI18N  
  44.   
  45.         myLabel.setText("Ok, the text is currently not loaded...");  
  46.   
  47.         loadData.setText("Load Data");  
  48.         loadData.addMouseListener(new java.awt.event.MouseAdapter() {  
  49.             public void mouseClicked(java.awt.event.MouseEvent evt) {  
  50.                 loadDataMouseClicked(evt);  
  51.             }  
  52.         });  
  53.   
  54.         myMessage.setColumns(20);  
  55.         myMessage.setRows(5);  
  56.         jScrollPane1.setViewportView(myMessage);  
  57.   
  58.         writeData.setText("Write Data");  
  59.         writeData.addMouseListener(new java.awt.event.MouseAdapter() {  
  60.             public void mouseClicked(java.awt.event.MouseEvent evt) {  
  61.                 writeDataMouseClicked(evt);  
  62.             }  
  63.         });  
  64.   
  65.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());  
  66.         getContentPane().setLayout(layout);  
  67.         layout.setHorizontalGroup(  
  68.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
  69.             .addGroup(layout.createSequentialGroup()  
  70.                 .addContainerGap()  
  71.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
  72.                     .addGroup(layout.createSequentialGroup()  
  73.                         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
  74.                             .addComponent(myLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)  
  75.                             .addComponent(jScrollPane1))  
  76.                         .addContainerGap())  
  77.                     .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()  
  78.                         .addGap(0, 0, Short.MAX_VALUE)  
  79.                         .addComponent(loadData)  
  80.                         .addGap(158, 158, 158))))  
  81.             .addGroup(layout.createSequentialGroup()  
  82.                 .addGap(154, 154, 154)  
  83.                 .addComponent(writeData)  
  84.                 .addGap(0, 0, Short.MAX_VALUE))  
  85.         );  
  86.         layout.setVerticalGroup(  
  87.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
  88.             .addGroup(layout.createSequentialGroup()  
  89.                 .addContainerGap()  
  90.                 .addComponent(myLabel)  
  91.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)  
  92.                 .addComponent(loadData)  
  93.                 .addGap(39, 39, 39)  
  94.                 .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)  
  95.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)  
  96.                 .addComponent(writeData)  
  97.                 .addContainerGap(82, Short.MAX_VALUE))  
  98.         );  
  99.   
  100.         pack();  
  101.     }// </editor-fold>                          
  102.   
  103.     private void loadDataMouseClicked(java.awt.event.MouseEvent evt) {                                        
  104.         // TODO add your handling code here:  
  105.         try {  
  106.             String data = controller.getMessage();  
  107.             myLabel.setText(data);  
  108.             myLabel.setVisible(true);  
  109.         } catch (Exception er) {  
  110.               
  111.         }  
  112.     }                                       
  113.   
  114.     private void writeDataMouseClicked(java.awt.event.MouseEvent evt) {                                         
  115.         // TODO add your handling code here:  
  116.         String message = myMessage.getText();  
  117.         controller.writeMessage(message);  
  118.     }                                        
  119.   
  120.     /** 
  121.      * @param args the command line arguments 
  122.      */  
  123.     public static void main(String args[]) {  
  124.         /* Set the Nimbus look and feel */  
  125.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">  
  126.         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
  127.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html  
  128.          */  
  129.         try {  
  130.             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {  
  131.                 if ("Nimbus".equals(info.getName())) {  
  132.                     javax.swing.UIManager.setLookAndFeel(info.getClassName());  
  133.                     break;  
  134.                 }  
  135.             }  
  136.         } catch (ClassNotFoundException ex) {  
  137.             java.util.logging.Logger.getLogger(HelloWorldView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
  138.         } catch (InstantiationException ex) {  
  139.             java.util.logging.Logger.getLogger(HelloWorldView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
  140.         } catch (IllegalAccessException ex) {  
  141.             java.util.logging.Logger.getLogger(HelloWorldView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
  142.         } catch (javax.swing.UnsupportedLookAndFeelException ex) {  
  143.             java.util.logging.Logger.getLogger(HelloWorldView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
  144.         }  
  145.         //</editor-fold>  
  146.   
  147.         /* Create and display the form */  
  148.         java.awt.EventQueue.invokeLater(new Runnable() {  
  149.             @Override  
  150.             public void run() {  
  151.                 new HelloWorldView().setVisible(true);  
  152.             }  
  153.         });  
  154.     }  
  155.   
  156.     // Variables declaration - do not modify                       
  157.     private javax.swing.JScrollPane jScrollPane1;  
  158.     private javax.swing.JButton loadData;  
  159.     public javax.swing.JLabel myLabel;  
  160.     private javax.swing.JTextArea myMessage;  
  161.     private javax.swing.JButton writeData;  
  162.     // End of variables declaration                     
  163. }  

The preceding code creates the View. In NetBeans, the IDE hides all of the fuzzy code and just displays the code that is required. In Eclipse you would be required to write it all. So that is why, you can use this code in the Eclipse to build the GUI.

The preceding code was a result of the drag-and-drop actions. I didn't write anything apart from function calls.

Creating the controller

The controller is the very vital section of our application. It contains the back-end code and the logic, for connecting the application's views (indirectly the user, because the user will use the view to interact with the application) with the models (the data source of our applications).

A similar process should be repeated. Create a new package, name it JavaMVCControllers, then create a new class and name it HelloWorldController. This class would control all of the logic of our application, so it is vital that this application has enough functions and flexibility to handle all of the events and requirements for our application. Such as, whenever the view needs to do something the controller must have a function defined to be triggered as well as for the model, to load the data from the Model into the View or to load the data from the View to the Model, to let the model save the data to the disk.

Once the class file has been generated write the following code for it.

  1. /* 
  2.  * To change this license header, choose License Headers in Project Properties. 
  3.  * To change this template file, choose Tools | Templates 
  4.  * and open the template in the editor. 
  5.  */  
  6. package JavaMVCControllers;  
  7.   
  8. import JavaMVCViews.*;  
  9. import JavaMVCModels.*;  
  10.   
  11. /** 
  12.  * 
  13.  * @author AfzaalAhmad 
  14.  */  
  15. public class HelloWorldController {  
  16.       
  17.     public void startApplication() {  
  18.         // View the application's GUI  
  19.         HelloWorldView view = new HelloWorldView();  
  20.         view.setVisible(true);  
  21.     }  
  22.       
  23.     public String getMessage() {  
  24.         try {  
  25.             HelloWorldModel model = new HelloWorldModel();  
  26.             return model.getData();  
  27.         } catch (Exception er) {  
  28.             return "There was an error.";  
  29.         }  
  30.     }  
  31.       
  32.     public boolean writeMessage(String message) {  
  33.         try {  
  34.             HelloWorldModel model = new HelloWorldModel();  
  35.             return model.writeData(message);  
  36.         } catch (Exception er) {  
  37.             return false;  
  38.         }  
  39.     }  
  40. }  

The controller here accesses the view package as well as the model package in our application. It contains three methods, one is the startApplication that starts the application's GUI by calling the view and setting it to be visible.

Another two functions just write the data to the model or extract the data from the model and return it to the view. The main function is the startApplication function. We would call this function, to actually start the application. Why is it so important? In Java's Swing API, a JFrame is set to be visible once its setVisible property is set to be true. That is why, inside this function, the GUI is visible and the application now looks like it just started. It can be thought of as the entry point of our MVC application inside our HelloJavaCollections project.

Handling the events in the View

There was a step left in the View that I skipped over for a later time and that time has come. In Swing, you can handle the events, such as mouse, keyboard or other calls that are made to the control. In our application, we're interested in the mouse events only to handle the mouse click event on the buttons.

In NetBeans you can right-click over the button (in the GUI builder) and the in the events, under the mouse click on the mouseClick event do something.

mouse click

The GUI builder will automatically add the code to handle the event and will let you write the code to execute once the trigger is made. For example, in our code, once the trigger was handled, the event to handle it was created and the GUI builder would take you to the source code panel and would let you write the code under the event. The two events in our application are the following:

  1. private void loadDataMouseClicked(java.awt.event.MouseEvent evt) {                                        
  2.     // TODO add your handling code here:  
  3.     try {  
  4.         String data = controller.getMessage();  
  5.         myLabel.setText(data);  
  6.         myLabel.setVisible(true);  
  7.     } catch (Exception er) {  
  8.               
  9.     }  
  10. }                                       
  11.   
  12. private void writeDataMouseClicked(java.awt.event.MouseEvent evt) {                                       
  13.     // TODO add your handling code here:  
  14.     String message = myMessage.getText();  
  15.     controller.writeMessage(message);  
  16. }   

These events would execute once the user clicks on the buttons, depending on which button is clicked.

Diving deeper, explaining more

Now the code has been set. The application is now set to run and work as we want it to. The controller is running and would run the view to render the application's GUI and the user can interact to load the data or to update the data in the file that is at the back-end as the data source.

Now, let us see how the application runs, what functions are called first and how the MVC pattern works in our small Hello world application. Starting from the first stage and moving all the way to the last stages in our application.

Running the application

When you run the application, as default (if you didn't change the behavior) the default entry point is set to the JavaHelloCollections class's Main function. The source code in the top of the article, is the one I'm talking about. If you run the application it won't show anything, because the function is empty and it would terminate without doing anything real. So, change the application and introduce the MVC pattern of our application. Like this:

  1. /* 
  2.  * To change this license header, choose License Headers in Project Properties. 
  3.  * To change this template file, choose Tools | Templates 
  4.  * and open the template in the editor. 
  5.  */  
  6. package javahellocollections;  
  7.   
  8. import JavaMVCControllers.*;  
  9.   
  10. /** 
  11.  * 
  12.  * @author AfzaalAhmad 
  13.  */  
  14. public class JavaHelloCollections {  
  15.   
  16.     /** 
  17.      * @param args the command line arguments 
  18.      */  
  19.     public static void main(String[] args) {  
  20.         // TODO code application logic here  
  21.         HelloWorldController controller = new HelloWorldController();  
  22.         // Start the application  
  23.         controller.startApplication();  
  24.     }  
  25. }  

What I did is, just added the controller and triggered the startApplication function in it. Now once this executes the application runs and the GUI would be visible.

Under the startApplication

Now let us see what happened when the startApplication was triggered. As soon as the startApplication was triggered the control moved over to the Controller. The controller now controls the application and every trigger must be made through the controller. The View and Model both depend on the controller now. It is not a good approach to let all of these three interact, it would kill the main purpose of the MVC pattern. Inside the Controller, the function is something like this:

  1. public void startApplication() {  
  2.     // View the application's GUI  
  3.     HelloWorldView view = new HelloWorldView();  
  4.     view.setVisible(true);  
  5. }  

 

my view app

View has been loaded

Up to this stage, the control is still in the hands of the controller, but not directly. Directly it seems as if the control were in the hands of the user using the application. Because no other code would execute until the user asks the application to do something, like close the application, load the data or save the data and so on. Once he orders something, then the controller would again act and would perform the action returning the control back to the hands of the user.

This method continues until the user interacts with the view himself. Now, let us run our application and see what our application shows us.

Note that the default look and feel set by the NetBeans is Nimbus, I didn't bother editing it.

 text not loaded

Now that the view has been loaded, let us tinker with it a little. Should we?

Loading/Writing the data

Now that the user has clicked on the load data button, the button was attached to an event that handles the click. Inside that event we're going to call the controller, to provide us with some data. We will be using that data from the controller to load into the JLabel we're having, the one showing "Ok, the text is currently not loaded".

  1. String data = controller.getMessage();  
  2. myLabel.setText(data);  
  3. myLabel.setVisible(true);  

To be sure that the changes are visible, you call this function to recreate the view and show it to the user.

MVC interaction

The preceding image that I drew shows how the controller, view and the model interact when the user wants to transmit the data or to receive the data. Let us assume the first event that loads the data and the view makes a request to the controller to provide the data. The controller then calls the model for the data. If the data is accessed then the data is returned back to the view, otherwise the error that errors can be multiple, ranging from unauthorized user, or disk errors. So it depends on many factors what sort of data would be returned.

Inside the getMessage

Inside the getMessage function, the call is now made to the model to load the data into our stream. The code for that in our application is:

  1. HelloWorldModel model = new HelloWorldModel();  
  2. return model.getData();  

Now this would return the data, based on the same preceding stream that I drew. The data would be captured by the controller and ed to the view for rendering. Let us see what happens in our code. In our application, the file doesn't yet exist so there won't be anything displayed to the user because the file is empty after the creation.

enter data

Now letting the user to write some data in the file. Then we will handle the same event once again, but with an opposite traffic. This time the data won't be coming from the data source to the view via the controller. But to the data source from the view via the controller.

Writing the data

Now, suppose the user filled in the value and clicked the write data button. What would happen? The controller would again come into action to perform the data store actions. You shouldn't connect your view to your data source directly.

  1. String message = myMessage.getText();  
  2. controller.writeMessage(message);  

The preceding code is simple, it gets the data from the text field and then requests the controller to write the message to the disk. Let us see what is under the hood there.

Inside the writeMessage

Inside this function, the model is again called, but in an opposite manner. The data ed is then stored on the disk inside that file.

  1. HelloWorldModel model = new HelloWorldModel();  
  2. return model.writeData(message);  

Now the model would store the data, depending on the methods and logic specified in the model class.

I have not talked about the methods in the model, because they're about the Java language itself and the Java IO API and has nothing to do with the MVC pattern.

Once the data is stored on the file, you can again request the data. Once again, following the MVC connection, the data comes from the data source via the controller all the way down to the view. The view rendered the data on the screen and then shows the data.

data stored

The data, once it returns, has something in it. So the Swing framework viewed it without any problem at all.

Points of Interest

In this article you learned about the MVC framework (pattern) of software development and how one can implement this framework in his software development, to distribute the source code into three layers.

  1. Model: For the data.

  2. View: For the user interface.

  3. Controller: For the back-end code.

In Java, you're required to install the SDK for Java and then an IDE supporting the Java programming language to develop applications. The application that is developed can have any programming architecture used in it. In our case we used the MVC framework, there are some others too like MVVM.

In Java, you combine and merge the similar classes into packages like you create a namespace in C# or C++. These packages are useful in distributing the code of the same category in various packages under a different name.

You can create as many package in an application as you want and then you can reference them in your projects. Classes of the same project do not need to import the classes, but the classes outside of your package need to make a reference to your package before they can access your classes.

In a MVC pattern, the data is not directly accessible by the user, instead the controller handles all the requests from and to the model to prove the validity and the consistency of the data. The view can trigger different commands, using which we can force the application to perform actions.

In MVC, you split the source code so that once the application reaches the level of enterprise solution you do not need to scratch your head or pull your hair just because your code looks fuzzy now. MVC allows you to maintain the code separately, focusing over one section at a time. Either that one is a view, a model or the controller itself. You can debug your application quicker by knowing which of the divisions needs your attention at the moment and leaving the other two as they are.

Up Next
    Ebook Download
    View all
    Learn
    View all