Java MVC Model View Controller Design Pattern

I was just reading a article on MVC and although very informative was the writer made a mountain out of a mole hill, ill attempt to break the idea down in code and I hope you can get the idea.

Ill use four classes to do this. 3 for the Model View Controller and 1 to start things off.

Model - The model manages the behavior of the data
View - The interface, this can be the webpage that the user uses.
Controller - The glue between the Model and the View


Design Pattern



---------------------------------------CODE -----------------------------------

class Start
{
public static void main(String args[])
{
               //INSTANTIATE CLASSES  GUI = VIEW AND CONT = CONTROLLER

gui newGUI = new gui();
Cont newCont = new Cont();
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////


import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import java.awt.GridLayout;


class gui extends JFrame
{
       /// CREATE ARRAY OF JBUTTONS FOR THE JFRAME
public JButton button[];

public gui()
{
button= new JButton[9];
GridLayout grid = new GridLayout(3,3);

               ////////////BUILD JFRAME PROPERTIES
                setSize(400,400);
setLayout(grid);

                ///ADD BUTTONS TO JFRAME
for(int loop=0; loop<9; loop++)
{
button[loop]= new JButton();
button[loop].setText(""+loop);
add(button[loop]);
}

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

       ////DISPLAY MESSAGE WHEN CONTROLLER PASSES VALUES BACK
public void displayResults(int x)
{
JOptionPane.showMessageDialog(null,x);
}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////


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


class Cont extends gui implements ActionListener
{
       ///INSTANTIATE MODEL CLASS 
Model newModel = new Model();

public Cont()
{
              ///ADD ACTIONLISTENER TO EACH BUTTON

for(int x=0; x<super.button.length; x++)
super.button[x].addActionListener(this);
}

public void actionPerformed(ActionEvent e)
{
for(int x=0; x<super.button.length; x++)
{
if(e.getSource()==super.button[x])
{
newModel.setNumber(x); //PASS VALUE TO MODEL
super.displayResults(newModel.getNumber()); //PASS RESULTS BACK TO VIEW (gui)
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////////


class Model
{
private int newNumber;

public void setNumber(int number)
{
newNumber = number;
}

public int getNumber()
{
return newNumber;
}
}


------------------------------------OUTPUT-----------------------------------

Model View Controller Java Code



No comments:

Post a Comment