0

I'm trying to get my head around the MVC design pattern using Swing in Java it's pretty confusing at the moment because I don't fully understand it. I have tried to make what I understand of it in eclipse but I have a error on line 68, I'm not sure why everytime I push a button I get a lot of errors being spat out and not the incrementing value of counter. Thanks

public class Model 
{
    int counter = 0;

    int counter()
    {
        this.counter++;
        return this.counter;
    }

}

#################################################################################
public class Controller 
{
    Model mRef;
    View vRef;

    public Controller(Model m, View v) 
    {
        this.mRef = m;
        this.vRef = v;
    }   

    int inc()
    {   
        mRef = new Model();
        return mRef.counter();
    }

}
######################################################################################
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class View extends JFrame
{
    JPanel jp;
    JButton jb1;
    JLabel jl1;
    GridBagConstraints c;
    Controller con; 
    public View()
    {       
        c = new GridBagConstraints();
        jp = new JPanel();
        jb1 = new JButton("First");
        jl1 = new JLabel("Label");
        jp.setLayout(new GridBagLayout());      
        add(jp);    

        c.gridx = 0;
        c.gridy = 0;
        jp.add(jb1, c);

        jb1.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                System.out.println(con.inc());
            }
        });
        c.gridx = 0;
        c.gridy = 2;
        jp.add(jl1, c);

        setVisible(true);
        pack(); 
    }
}
Definity
  • 691
  • 2
  • 11
  • 31
  • 1
    con is null when your actionPerformed method is called, however, your view should be talking to the model, the controller should be registering interest in the button and handling the actionPerforned event. Beware, Swing does not strict implement MVC, its more like M(VC) – MadProgrammer May 24 '14 at 23:46
  • More on the topic may be found [here](http://stackoverflow.com/a/3072979/230513). – trashgod May 24 '14 at 23:56

1 Answers1

0

I recommend to consider using JavaFX, is simpler and prettier than Swing. It provides you with what is called a Scene Builder, where you can easily drag and drop controls to your user interface.

In the following link you can install the Scene Builder under Additional Resources.

http://www.oracle.com/technetwork/java/javase/downloads/index.html

presa
  • 195
  • 4
  • 12