Book Creator

MVC Pattern in Java with Netbeans

by Brad Baez


MVC Pattern in Java with Netbeans

Comic Panel 1
First, Create a new proyect in Netbeans
For this example, the name of project will be jc_mvc_demo.

Create a package structure (Controller, Model, View), we do this to separate each component, to be more organized. You should have something like this.
As you can see, we keep the default package together with the that Netbeans creates for us, our "launcher".
2.Next step, Let's start creating the application logic

Create a new class in the Model package, call it "" and add the following code:
Netbeans, when adding objects to our JFrame, automatically places them as PRIVATE, we must change this, to do this select the object "vtxt1" and go to its properties, in the CODE tab, choose the field VARIABLE MODIFIERS, in the window that appears, change the PRIVATE attribute, by PUBLIC and click on accept. Repeat this action for all the objects that are marked with red in the previous image.
Explanation: our controller class, implements the ActionListener, this to respond from this class, the events made from the interface (VIEW), also in the constructor of the class, we see that are passed as parameters, the VIEW class and the MODEL class, our class also has the functions, INITIATE() which initializes the values of the interface, such as the title attribute of the JFrame, positioning on screen, initial values of the jtextbox, etc.. We also have the performed action method which captures the event performed from the interface, in our example it is just a CLICK ON THE MENU BUTTON CMDSUMAR, obtains the corresponding data and invokes the model to process the information and obtain a response.

To finish we must implement all this in our
3.Now, we continue with the CONTROLLER of our application

Create a class "" in the CONTROLLER package, the code you must place is:
Finally, run the program
The MVC pattern allows us to change the user interface (VIEW), without touching the application MODEL at all, and to make small changes in the controller, minimal changes, as we can see in the image above.
Comic Panel 1