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 projects, depending on the sort of the software 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 three of your layers separate.  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 it 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 they are allowed.  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 complicated and all three segments of the application interfere with each other, in a single source code package . This way, you 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 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.  Instead, they must interact with the top-level layers, to access the data.  Such as, for the view, they interact 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 a potential user.
 
I wrote an article about the ASP.NET MVC framework.  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.  Only, 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.
 

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 of the popular ones 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 the Oracle license and is mostly used by beginners, because 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.  It depends on which level of application you're going to develop.  There are many types of Java SDKs available for you and you can choose from among them.  I am using the Java SE SDK.  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 too complex.
     
  2. Java EE: Enterprise edition.  Should be preferred over Java SE, if you're going to develop an enterprise application and the program is 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 on 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. Learn more here.
You can download any SDK, and the Java language would be similar.  So, the code in my article would be a good fit, 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.  This is a simple task, but a bit confusing for beginners.  Go to the properties of "My Computer" and inside the Advanced system settings, then Environment variables.  Inside it, create a new system variable and name it JAVA_HOME.  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 will 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. I f 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. package javahellocollections;  
  2. public class JavaHelloCollections {  
  3.  public static void main(String[] args) {}  
  4. }  
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, 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 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.  There is no requirement to follow to create the view first, then create a controller to render the view, and then create a model to add data.  We can start by creating a section, 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.  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.   // Save the data to the File    
  56.   try (BufferedWriter writer = new BufferedWriter(  
  57.    new FileWriter("F:\\file.txt"))) {  
  58.    // Write the data to the File    
  59.    writer.write(data);  
  60.    // Return indicating the data was written    
  61.    return true;  
  62.   } catch (Exception er) {  
  63.    return false;  
  64.   }  
  65.  }  
  66. }   
The preceding code can be explained in the following few stages:
  1. First, 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. 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 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).  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.  It contains enough controls for our application to work like it must.  The View's work is to display what controller is allowed.  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. package JavaMVCViews;  
  2. import JavaMVCControllers.*;  
  3. public class HelloWorldView extends javax.swing.JFrame {  
  4.  private HelloWorldController controller = new HelloWorldController();  
  5.  public HelloWorldView() {  
  6.   initComponents();  
  7.  }  
  8.  @SuppressWarnings("unchecked")  
  9.  private void initComponents() {  
  10.   myLabel = new javax.swing.JLabel();  
  11.   loadData = new javax.swing.JButton();  
  12.   jScrollPane1 = new javax.swing.JScrollPane();  
  13.   myMessage = new javax.swing.JTextArea();  
  14.   writeData = new javax.swing.JButton();  
  15.   setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);  
  16.   setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));  
  17.   setName("myFrame");  
  18.   myLabel.setText("Ok, the text is currently not loaded...");  
  19.   loadData.setText("Load Data");  
  20.   loadData.addMouseListener(new java.awt.event.MouseAdapter() {  
  21.    public void mouseClicked(java.awt.event.MouseEvent evt) {  
  22.     loadDataMouseClicked(evt);  
  23.    }  
  24.   });  
  25.   myMessage.setColumns(20);  
  26.   myMessage.setRows(5);  
  27.   jScrollPane1.setViewportView(myMessage);  
  28.   writeData.setText("Write Data");  
  29.   writeData.addMouseListener(new java.awt.event.MouseAdapter() {  
  30.    public void mouseClicked(java.awt.event.MouseEvent evt) {  
  31.     writeDataMouseClicked(evt);  
  32.    }  
  33.   });  
  34.   javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());  
  35.   getContentPane().setLayout(layout);  
  36.   layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(myLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE).addComponent(jScrollPane1)).addContainerGap()).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addGap(00, Short.MAX_VALUE).addComponent(loadData).addGap(158158158)))).addGroup(layout.createSequentialGroup().addGap(154154154).addComponent(writeData).addGap(00, Short.MAX_VALUE)));  
  37.   layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(myLabel).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(loadData).addGap(393939).addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(writeData).addContainerGap(82, Short.MAX_VALUE)));  
  38.   pack();  
  39.  }  
  40.  private void loadDataMouseClicked(java.awt.event.MouseEvent evt) {  
  41.   try {  
  42.    String data = controller.getMessage();  
  43.    myLabel.setText(data);  
  44.    myLabel.setVisible(true);  
  45.   } catch (Exception er) {}  
  46.  }  
  47.  private void writeDataMouseClicked(java.awt.event.MouseEvent evt) {  
  48.   String message = myMessage.getText();  
  49.   controller.writeMessage(message);  
  50.  }  
  51.  public static void main(String args[]) {  
  52.   try {  
  53.    for (javax.swing.UIManager.LookAndFeelInfo info: javax.swing.UIManager.getInstalledLookAndFeels()) {  
  54.     if ("Nimbus".equals(info.getName())) {  
  55.      javax.swing.UIManager.setLookAndFeel(info.getClassName());  
  56.      break;  
  57.     }  
  58.    }  
  59.   } catch (ClassNotFoundException ex) {  
  60.    java.util.logging.Logger.getLogger(HelloWorldView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
  61.   } catch (InstantiationException ex) {  
  62.    java.util.logging.Logger.getLogger(HelloWorldView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
  63.   } catch (IllegalAccessException ex) {  
  64.    java.util.logging.Logger.getLogger(HelloWorldView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
  65.   } catch (javax.swing.UnsupportedLookAndFeelException ex) {  
  66.    java.util.logging.Logger.getLogger(HelloWorldView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
  67.   }  
  68.   java.awt.EventQueue.invokeLater(new Runnable() {  
  69.    @Override  
  70.    public void run() {  
  71.     new HelloWorldView().setVisible(true);  
  72.    }  
  73.   });  
  74.  }  
  75.  private javax.swing.JScrollPane jScrollPane1;  
  76.  private javax.swing.JButton loadData;  
  77.  public javax.swing.JLabel myLabel;  
  78.  private javax.swing.JTextArea myMessage;  
  79.  private javax.swing.JButton writeData;  
  80. }  
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. package JavaMVCControllers;  
  2. import JavaMVCViews.*;  
  3. import JavaMVCModels.*;  
  4. public class HelloWorldController {  
  5.  public void startApplication() {  
  6.   HelloWorldView view = new HelloWorldView();  
  7.   view.setVisible(true);  
  8.  }  
  9.  public String getMessage() {  
  10.   try {  
  11.    HelloWorldModel model = new HelloWorldModel();  
  12.    return model.getData();  
  13.   } catch (Exception er) {  
  14.    return "There was an error.";  
  15.   }  
  16.  }  
  17.  public boolean writeMessage(String message) {  
  18.   try {  
  19.    HelloWorldModel model = new HelloWorldModel();  
  20.    return model.writeData(message);  
  21.   } catch (Exception er) {  
  22.    return false;  
  23.   }  
  24.  }  
  25. }  
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 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 in the events, under the mouse click on the mouseClick event to 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 was created.  The GUI builder, would then, 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. }  
  17. These events would execute once the user clicks on the buttons, depending on which button is clicked.  
  18.   
  19. Diving deeper, explaining more  
  20.   
  21. 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.  
  22.   
  23. Now,  
  24. 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.  
  25.   
  26. Running the application  
  27.   
  28. When you run the application, as  
  29. default (  
  30.  if you didn 't change the behavior) the default entry point is set to the JavaHelloCollections class'  
  31.  s Main  
  32.  function.The source code in the top of the article, is the one I 'm talking about. If you run the application it won'  
  33.  t show anything, because the  
  34.  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:  
  35.  /*  
  36.   * To change this license header, choose License Headers in Project Properties.  
  37.   * To change this template file, choose Tools | Templates  
  38.   * and open the template in the editor.  
  39.   */  
  40.  package javahellocollections;  
  41.   
  42.  import JavaMVCControllers.*;  
  43.   
  44.  /**  
  45.   *  
  46.   * @author AfzaalAhmad  
  47.   */  
  48.  public class JavaHelloCollections {  
  49.   
  50.   /**  
  51.    * @param args the command line arguments  
  52.    */  
  53.   public static void main(String[] args) {  
  54.    // TODO code application logic here    
  55.    HelloWorldController controller = new HelloWorldController();  
  56.    // Start the application    
  57.    controller.startApplication();  
  58.   }  
  59.  }  
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.  Now, the View and Model both depend on the controller. It is not a good approach to let all three of these 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.  HelloWorldView view = new HelloWorldView();  
  3.  view.setVisible(true);  
  4. }  
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.  Such as, 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 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 have drawn, 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, let the user 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  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 their 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 others 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 packages 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, in 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 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.


Similar Articles