MVC Java Tutorial

MVC Java TutorialWelcome to my MVC Java Tutorial. I have been asked for this tutorial many times in the last few weeks.

To understand the Model View Controller you just need to know that it separates the Calculations and Data from the interface. The Model is the class that contains the data and the methods needed to use the data. The View is the interface. The Controller coordinates interactions between the Model and View.

The video and code below will make it very easy to understand.

If you like videos like this it helps to tell Google+

Code From the Video

CalculatorModel.java

// The Model performs all the calculations needed
// and that is it. It doesn't know the View 
// exists

public class CalculatorModel {

	// Holds the value of the sum of the numbers
	// entered in the view
	
	private int calculationValue;
	
	public void addTwoNumbers(int firstNumber, int secondNumber){
		
		calculationValue = firstNumber + secondNumber;
		
	}
	
	public int getCalculationValue(){
		
		return calculationValue;
		
	}
	
}

CalculatorView.java

// This is the View
// Its only job is to display what the user sees
// It performs no calculations, but instead passes
// information entered by the user to whomever needs
// it. 

import java.awt.event.ActionListener;

import javax.swing.*;

public class CalculatorView extends JFrame{

	private JTextField firstNumber  = new JTextField(10);
	private JLabel additionLabel = new JLabel("+");
	private JTextField secondNumber = new JTextField(10);
	private JButton calculateButton = new JButton("Calculate");
	private JTextField calcSolution = new JTextField(10);
	
	CalculatorView(){
		
		// Sets up the view and adds the components
		
		JPanel calcPanel = new JPanel();
		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setSize(600, 200);
		
		calcPanel.add(firstNumber);
		calcPanel.add(additionLabel);
		calcPanel.add(secondNumber);
		calcPanel.add(calculateButton);
		calcPanel.add(calcSolution);
		
		this.add(calcPanel);
		
		// End of setting up the components --------
		
	}
	
	public int getFirstNumber(){
		
		return Integer.parseInt(firstNumber.getText());
		
	}
	
	public int getSecondNumber(){
		
		return Integer.parseInt(secondNumber.getText());
		
	}
	
	public int getCalcSolution(){
		
		return Integer.parseInt(calcSolution.getText());
		
	}
	
	public void setCalcSolution(int solution){
		
		calcSolution.setText(Integer.toString(solution));
		
	}
	
	// If the calculateButton is clicked execute a method
	// in the Controller named actionPerformed
	
	void addCalculateListener(ActionListener listenForCalcButton){
		
		calculateButton.addActionListener(listenForCalcButton);
		
	}
	
	// Open a popup that contains the error message passed
	
	void displayErrorMessage(String errorMessage){
		
		JOptionPane.showMessageDialog(this, errorMessage);
		
	}
	
}

CalculatorController.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

// The Controller coordinates interactions
// between the View and Model

public class CalculatorController {
	
	private CalculatorView theView;
	private CalculatorModel theModel;
	
	public CalculatorController(CalculatorView theView, CalculatorModel theModel) {
		this.theView = theView;
		this.theModel = theModel;
		
		// Tell the View that when ever the calculate button
		// is clicked to execute the actionPerformed method
		// in the CalculateListener inner class
		
		this.theView.addCalculateListener(new CalculateListener());
	}
	
	class CalculateListener implements ActionListener{

		public void actionPerformed(ActionEvent e) {
			
			int firstNumber, secondNumber = 0;
			
			// Surround interactions with the view with
			// a try block in case numbers weren't
			// properly entered
			
			try{
			
				firstNumber = theView.getFirstNumber();
				secondNumber = theView.getSecondNumber();
				
				theModel.addTwoNumbers(firstNumber, secondNumber);
				
				theView.setCalcSolution(theModel.getCalculationValue());
			
			}

			catch(NumberFormatException ex){
				
				System.out.println(ex);
				
				theView.displayErrorMessage("You Need to Enter 2 Integers");
				
			}
			
		}
		
	}
	
}

MVCCalculator.java

public class MVCCalculator {
    
    public static void main(String[] args) {
    	
    	CalculatorView theView = new CalculatorView();
        
    	CalculatorModel theModel = new CalculatorModel();
        
        CalculatorController theController = new CalculatorController(theView,theModel);
        
        theView.setVisible(true);
        
    }
}

87 Responses to “MVC Java Tutorial”

  1. Punit says:

    kool man.
    also waiting for your game development tutorial.

  2. Kingzad says:

    Thanks for the very useful Videos! I have always wonder shouldn’t the model store ALL the data that is going to be displayed in view like first_number and second_number as well? Assume an example where the first_number is the score of a student out of total marks which is the 2nd number. The sample function is going to just calculate the % of the student in the test. Assume the view wants to print the whole report of student later, it could just ask the model for that information? What do you think? Thanks again!

    • Derek Banas says:

      There are many ways to implement an MVC. Yes you are correct that model should contain all of the data, but when I am implementing a system I tend to decouple the model completely from the view if possible. I could have kept them decoupled and still store the numbers in the model with a FocusListener, but I was also trying to keep the code as uncomplicated as possible. I hope that clears some things up. You made a good point 🙂

  3. Ognian says:

    Thanks for the very useful Videos!

  4. Sbo says:

    Thank you so much for this awesome tutorial. I was wondering if you could clarify the MVC design pattern with regards to Servlets, JSPs and Java classes. my main issue is the communication between the Controller(Servlet) and the view(JSP). and is it the best way to implement MVC if you have your model create certain parts of the view EG:a Table, then pass it on as a String value to the Controller which in-turn sends it to the view to display.To communicate(Controller and VIEW) I’m currently using JQUERY,AJAX AND JSON

    • Derek Banas says:

      I’ll cover JEE concepts as soon as possible. I go out of my way to avoid having the model do anything but handle data and process data. I try to have the controller handle all communications between the Model and View.

      This isn’t the only MVC pattern by any means though. Many allow the model and view to interact. If the code is understandable I have no problem with that.

  5. Ognian says:

    Perfect video!

  6. game6 says:

    Hello! Incredible tutorial, but I have one question, if you can help me. How you work in the controller class if you have a model made by 2 classes for example?

    • Derek Banas says:

      Thank you very much 🙂 The controller would just work with both of them. Not much would change here. It is all about the action listeners and triggering the right methods when needed. Sorry, I can’t really say anything else because I’m not sure what may be hanging you up

  7. PJames says:

    Excellent tutorial. I am just started learning about MVC and this is the best job I have seen explaining it.

    I would tweak one tiny thing to the actual program… I added:
    calcSolution.setEditable(false);
    because it seemed odd that I could type a value into the solution field.

    Love the site. Just found it and I will be spending a lot of time here!

  8. Hi Derek!

    I’m from Queretaro Mexico, dude I really love your site, your work is just amazing.

    I’ve a question, hopefully you can guide me, for example, if I have two or more buttons in my main window and each one has a different action, should I create one inner class in my controller for each different button ? Is that the right way to do it ?

    I can’t thank you enough!

    • Derek Banas says:

      You’re very welcome 🙂

      Basically you need to define what method to call in the controller when the button is clicked in the view like this

      // If the calculateButton is clicked execute a method
      // in the Controller named actionPerformed
      void addCalculateListener(ActionListener listenForCalcButton){
      calculateButton.addActionListener(listenForCalcButton);
      }

      Then everything is handled in the controller like this

      class CalculateListener implements ActionListener{
      public void actionPerformed(ActionEvent e) {…

      Does that help?

  9. Arild says:

    Easy does it… Nice tutorial.

  10. A Phillips says:

    Awesome tutorial! I’ve been out of the programming realm for a while now, but I want back in, and recently I saw MVC as preferred knowledge for a job opening. Google got me to your tutorial, and I must say I have a great understanding of what’s involved in MVC. Now I just have to reinvent my programming methods, which are pretty rusty and outdated anyway.

    To tell the truth though, I don’t understand 100% why the view and controller are separate…

    • Derek Banas says:

      Thank you 🙂 A major step for a programmer is investing some time into understanding object oriented programming completely. That is probably what you are struggling with? The whole idea behind MVC is to separate the components so that they can be changed without breaking, or even effecting the rest of the system. Just like how we can put new windshield whippers on our car with worrying about the whole car breaking.

      I explain Object Oriented Design in detail here. It should help you better understand the process

  11. Sufia Ali says:

    Awesome tutorial. I just started learning MVC and I have couple of questions:

    1) So, the whole concept of MVC is to break down the code into seperate programs to make coding more clear, is that true? Meaning, instead of writing 1 program with thousand lines of code, we break down into 3 different programs (1 for model, 1 for view, and for controller). Is that correct?

    2) I want to practice using Eclipse and copy your code and play with it. Can you tell me what I need to do? Do I download Eclipse? How do I set it up? What else do I need to download in order to follow your Calculator code?

    3) Can you give me another tutorial like this but using SQL database? Like an address book scenario. Can you please explain to me?

    • Derek Banas says:

      1. MVC is used for many reasons. It helps break pieces of your system into real world objects. It also makes it easy for you to change the model and view without breaking your program because the controller handles communications between the two.

      2. I cover how to install eclipse for java here.

      3. Right now I’m making Android tutorials. I will make a tutorial using SQLite very soon and I’ll use the MVC with it

      I hope that helps

  12. Dwi Prawira says:

    Awesome tutorial,
    but i have small question.

    So the Main function can directly access to theView?

    Isn’t it should be theController that set theView to be visible?

    Thanks for the answer,,

    • Derek Banas says:

      Thank you 🙂 Main could access the view, but the controller does all of the work. I don’t want to tightly couple the view and controller by having the view created by the controller. Does that help?

  13. markuz says:

    This is the simplest, easiest and the clearest example of MVC I’ve ever found. Thanks.

  14. Michael says:

    Hi

    I find your tutorial very useful. I have created a view made up of three input components. Two of these provide the filling for sql stored procedures executed by the controller.

    I have created a model for each of these components. There is only one controller. Is this the best way to do it?

    What is the best way of identifying which button was clicked, there are three. Would you use the onFormEvent or just use an action event on the buttons involved. How would you update the model and view from a controller that ran a sql stored procedure.

    Thanks

    Michael

    • Derek Banas says:

      Sounds like you set up everything well. For something like that it makes sense to have just one controller.

      I’d monitor action events like you said to make updates for the view. Great job!

      Derek

  15. Wing says:

    Hi, great tutorial. If I had watched it a year ago, I could had done a better job 😛

    I have some questions by the way.

    1. If I have difernt views (forms) I need a different controller for each one?
    2. How do I stablish communication between different controllers?
    3. Do you have a DOA pattern example?

    Thank you very much for such a great example.

    Ricardo.

    • Derek Banas says:

      Hi Ricardo,

      Thank you very much 🙂 I’m glad you enjoyed it.

      1. You should have 1 controller in most all situations no matter how many views you have. You can have many models and many views however.

      2. Not Applicable

      3. Sorry I haven’t covered that pattern yet, but I will when I cover JEE topics.

      Derek

  16. Cris tan says:

    Is MVC a design pattern? If not what type of deign pattern ? Thanks

  17. No5 says:

    Thank you very much for you article!

  18. azzmi says:

    very goooood tutorial
    when one start with your tutorial ..can’t stop

  19. Julie says:

    Hello Derek,
    Thanks for the wonderful tutorial.
    I have a question: How exactly is this different from MVP, Model- View-Presenter? I thought that in MVC the model updates the view, whereas in MVP the controller liaises between the View and the Model (which is what you’re doing in this tutorial).

  20. David says:

    A very good example , thank U .

  21. Mark Brading says:

    Great tutorial, nice and straight forward 🙂

    The MVC pattern shown here demonstrates changing the model data by interacting with the view which is fine, but how would one change the model data by having the two numbers initially stored in a file and then reading those numbers so that the Model and View are updated? Lets say we have defined class that reads the file and stores the two numbers in instance variables of that class. How does that class fit into the MVC pattern?

    • Derek Banas says:

      Thank you 🙂 That is why the MVC is so brilliant. If you need to add a feature and the user asks for that feature everything changes accordingly, but they still don’t need to know how the task is performed.

      1. The view updates to allow the new feature if it must.
      2. The controller catches the request from the view and passes it to the model.
      3. The model performs the needed calculations and then sends them to the controller.
      4. The controller provides an update to the view.
      5. Anything can change and as long as we can agree on a solid way to communicate we don’t lose flexibility.

      I hope that answered your question.

  22. Rahul Sharma says:

    Hey Derek,
    If we try to implement this Calculator in Business Delegate along with MVC(in single code), so could you tell me ‘who will do what?’
    I mean
    Business Delegate’ service = MVC’s Model
    but what component of Business delegate will play role of controller
    and similarly where we can put VIEW component in business delegate…
    thank you so much in advance!!!

  23. idir says:

    Hi Derek,

    Thanks for all these tutorials, they are great.
    I still do have a probleme with the MVC pattern. How can we implement it with multiple views and models ? I’ve been googling around

    in advance, thanks for your response.

    • Derek Banas says:

      Hi,

      You may want to take a look at my Android tutorials because everything is based on MVC. You basically have one controller that handles all communication between the views and the models. If the view needs to change it tells the controller and it serves up a new view. If a new calculation is needed in the model the class is added and the controller just needs a way to communicate with that new class.

  24. Shohan says:

    A very helpful tutorial indeed!!! go ahead!!!

  25. Olaf says:

    Very nice example, just I have a question, how can I do to use some Controllers not only one? I need to create some class that would be working like a “Dispatcher”??

    I hope you can answer to me!
    Thanks in advance!

    • Derek Banas says:

      Thank you 🙂 The idea behind the MVC is to only have one controller. I may not have explained that well in the tutorial. I’ll make a new MVC tutorial to cover the issues that have been brought up.

  26. Leigh says:

    Great stuff, thanks. Nice and simple and to the point

  27. Shamiel says:

    Wow, so clear and easy. Thank you so much, this is good stuff.

  28. Franco says:

    Thank you man… 🙂 you explained it well. now its easy for me to manipulate the codes. once again thanks a lot.

  29. live reverof says:

    hey dude i saw your many tutorials and they are great
    and i also decided to run YouTube channel for java programming
    but i don’t know where to start ,technically i ran out of
    ideas for it because there are lot of tutorials in YouTube .
    so if you have any suggestion about where to kickoff it will helpful to me
    well you can also suggest some software development books on java
    thanks and keep making tutorials they are really fun to watch

  30. poonam says:

    Thank you!!!!!!!!!!!!

  31. pierre says:

    Hi Derek, Sorry that I’m bit off the topic, but do you use any autocomplete plugin for eclipse or just Ctrl+space?

  32. Dave says:

    Can anyone help me? I’m new to Java as well as MVC. I made the program work by following the tutorial, but is there any more models for MVC instead of a Calculator model? or does it depend on what we put inside the java to make it look and work like a calculator?

    Thankyou!

    • Derek Banas says:

      MVC is all about separating the interface (view) from the backend code (model). There are many different types of views and models, but they way they interact is basically the same.

  33. Raj kurki says:

    The tutorials are nice , the way it is covered.

  34. oldernewbee says:

    Fantastic explanation of rationale and implementation. Stream of consciousness coding works well. We want more!

  35. Vladimir says:

    Very concise illustrative example, much appreciated.

  36. Janak says:

    This was very useful in learning about the MVC.

    Can u please show or point me to a simple java application(code) that is developed according to the MVC which uses a database.

  37. Hitesh says:

    This is amazing! I never thought we can MVC in swing!

  38. Logan Mitchell says:

    Thank you for this tutorial!! It definitely cleared things up about the basic structure of the MVC model.

    I do have a question, though: You mentioned in a response to another commenter that a project could have many models and views but should only have one controller. Could you explain or demo how to have this program call and display the solution in a different view when the user clicks ‘Calculate’?

    I’m trying to understand how the controller gets any other view or model than the ones you passed to it from your main class.

    • Derek Banas says:

      You’re very welcome 🙂 You could definitely have multiple MVCs in one project. It is very common though for a controller to implement an ActionListener and contain a List of ActionListeners to maintain multiple models and views for example.

Leave a Reply

Your email address will not be published.

Google+