I have an Idea to develop a java Swing application using the MVC pattern. I have described my idea below and please let me know that, is this a correct way of using the MVC pattern for java Swing?
- this is the view

following methods are used to get and set the name of the above view,
//at top of the view its model and controller is defined as
Model model = null;
Controller controller = null;
//constructor
public view(){
this.model = new Model();
this.controller = new Controller(this, model);//controller takes view and model as its parameters.
}
public void v_addShowNameButtonsActionListener(ActionListener al){
btnActionListener.addActionListener(al);
}
public String v_getName(){
return txtName.getText();// txtName is the name of the text field.
}
public void v_setName(String name){
txtName.setText(name);
}
- this is the controller
/*at the top of the controller define the view and model*/ View view = null; Model model = null; /* constructor of the controller*/ public Constructor(View view, Model model){ this.view = view; this.model = model; } class CreateShowNameButtonsActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { Connection con = null; try{ con = ******************** /*get the data base connection*/ view.setName(model.m_getName(con)); }catch(Exception ex){ ex.printStackTrace(); }finally{ con.close(); } } }
- this is the model
Public class Model{ public String m_getName(Connection con){ String name; name = ******* //do database queries and set get the name form the database return name; } }
I have briefly described the way I am going to implement the MVC pattern in java Swing.
A change I would make maybe would be to do all database related operations within the model, that is, even managing my own database connections. This will allow the
Controllerclass to be completely independent from the where and the how you get the data.All that the
Controllerneeds to know is that it needs to call theModelto get whatever information it needs to eventually pass on to theView.As an extra note as well, it is usually a good idea to implement an extra layer between the
Controllerand theModel, known as aServicelayer. This usually comes in handy when you also need to expose certain similar functionality through other means, such as REST. This will allow you to write all your queries in theModellayer, then, any extra customization will be done within theServicelayer. This will allow theControllerand REST API to deliver the same functionality without either cluttering theModellayer or else have duplicate code in theControllerand REST API.