Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: MVC Calculator:

  1. #1
    Member
    Join Date
    Apr 2014
    Posts
    219
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default MVC Calculator:

    @GregBrandon

    I took your advice and I made a MVC calculator. I was wondering if you could take a look at my design and if I was on track. I am still working on getting it to actually calculate something. All the buttons respond and print text on the JTextField but it is not calculating, I am sure I will figure it out. I just wanted to share, and if you happen to see what I am doing wrong that would be helpful of course.

    model:
    package calculator.MVC;
     
    import javax.swing.JButton;
    import javax.swing.JTextField;
     
    public class CalculatorModel
    {
    	private int sum;
    	private int number;
    	private char opt;
     
    	public CalculatorModel()
    	{
    		sum = 0;
    		number = 0;
    	}
     
    	public void set(JButton idenifier, JTextField number)
    	{
    		//this will receive '+' '-' '/' etc
    		opt = idenifier.getText().charAt(0);
     
    		//getting value from JTextField and setting it as a integer
    		this.number = Integer.parseInt(number.getText());
     
    		calculate(opt);
    	}
     
    	public void setNumber(int number)
    	{
    		this.number = number;
    	}
     
    	public int getSum() {
    		return sum;
    	}
     
    	private void setSum(int sum) 
    	{
    		this.sum = sum;
    	}
     
    	void calculate(char sign)
    	{
    		switch(sign)
    		{
    		case '+':
    			sum += number; 
    			setSum(sum);
    			break;
    		case '-':
    			sum -= number;
    			setSum(sum);
    			break;
     
    		case '/':
    			sum/= number;
    			setSum(sum);
    			break;
     
    		case '*':
    			sum *= number;
    			setSum(sum);
    			break;
     
    		case '=':
    			setSum(sum);
    			break;
    		case 'C':
    			opt = 0;
    			number = 0;
    			sum = 0;
    			setSum(sum);
    			break;
    			default: 
    		}
    	}
    }

    view:
    package calculator.MVC;
     
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
     
    import javax.swing.*;
     
    public class CalculatorView
    {
    	JButton oneBtn, twoBtn, threeBtn, fourBtn, fiveBtn;
    	JButton sixBtn,sevenBtn, eightBtn, nineBtn, zeroBtn;
    	JButton addBtn, subtractBtn, multiplyBtn, divideBtn;
    	JButton resetBtn, equalsBtn;
     
    	JTextField textFeild;
     
    	JFrame frame;
     
    	JPanel numbersPanel, signsPanel;
     
    	CalculatorView()
    	{
    		frame = new JFrame("Simple Calculator");
    		frame.setSize(300,300);
    		frame.setLayout(new BorderLayout());
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		textFeild = new JTextField(10);
     
    		JPanel numbersPanel = new JPanel();
    		JPanel signsPanel = new JPanel();
     
    		numbersPanel = numberPan(numbersPanel); 
    		signsPanel = signPan(signsPanel);
     
    		frame.add(textFeild,BorderLayout.PAGE_START);
    		frame.add(numbersPanel,BorderLayout.CENTER);
    		frame.add(signsPanel,BorderLayout.LINE_END);
     
    		frame.setResizable(false);
    		frame.setVisible(true);
    	}
     
    	//returns a matrix of buttons to represent the numbers
    	//on the calculator
    	JPanel numberPan(JPanel panel)
    	{
    		oneBtn = new JButton("1");
    		twoBtn = new JButton("2");
    		threeBtn = new JButton("3");
    		fourBtn= new JButton("4");
    		fiveBtn= new JButton("5");
    		sixBtn= new JButton("6");
    		sevenBtn= new JButton("7");
    		eightBtn= new JButton("8");
    		nineBtn= new JButton("9");
    		zeroBtn= new JButton("0");
     
    		panel.add(sevenBtn);
    		panel.add(eightBtn);
    		panel.add(nineBtn);
    		panel.add(fourBtn);
    		panel.add(fiveBtn);
    		panel.add(sixBtn);
    		panel.add(oneBtn);
    		panel.add(twoBtn);
    		panel.add(threeBtn);
    		panel.add(zeroBtn);
     
    		panel.setLayout(new GridLayout(3,4));
     
    		return panel;
    	}
     
    	//return a horizontal pattern of buttons to represent
    	//the mathematical signs of the calculator
    	JPanel signPan(JPanel panel)
    	{
    		addBtn= new JButton("+");
    		addBtn.setPreferredSize(new Dimension(10,10));
    		subtractBtn= new JButton("-");
    		multiplyBtn= new JButton("*");
    		divideBtn= new JButton("/");
     
    		resetBtn= new JButton("C");
    		equalsBtn= new JButton("=");
     
    		panel.add(resetBtn);
    		panel.add(addBtn);
    		panel.add(subtractBtn);
    		panel.add(multiplyBtn);
    		panel.add(divideBtn);
    		panel.add(equalsBtn);
     
    		panel.setLayout(new GridLayout(3,3));
     
    		return panel;
    	}
     
    	void setTextValue(int value)
    	{
    		//sets textField to String value
    		textFeild.setText(Integer.toString(value));
    	}
     
    	//returns number currently in TextBox
    	int getTextFeildValue()
    	{
    		int value = Integer.parseInt(textFeild.getText());
     
    		return value;
    	}
     
     
     
    }

    controller:
    package calculator.MVC;
     
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
    public class CalculatorController 
    {
    	CalculatorModel model;
    	CalculatorView view;
     
    	CalculatorController(CalculatorModel model,CalculatorView view)
    	{
    		this.model = model;
    		this.view = view;
     
    		//setting action listeners for each button in the view class
    		view.addBtn.addActionListener(new Actions());
    		view.subtractBtn.addActionListener(new Actions());
    		view.multiplyBtn.addActionListener(new Actions());
    		view.divideBtn.addActionListener(new Actions());
    		view.equalsBtn.addActionListener(new Actions());
    		view.resetBtn.addActionListener(new Actions());
    		view.oneBtn.addActionListener(new Actions());
    		view.twoBtn.addActionListener(new Actions());
    		view.threeBtn.addActionListener(new Actions());
    		view.fourBtn.addActionListener(new Actions());
    		view.fiveBtn.addActionListener(new Actions());
    		view.sixBtn.addActionListener(new Actions());
    		view.sevenBtn.addActionListener(new Actions());
    		view.eightBtn.addActionListener(new Actions());
    		view.nineBtn.addActionListener(new Actions());
    		view.zeroBtn.addActionListener(new Actions());
    	}
     
    	//inner class that will handle action listeners
    	class Actions implements ActionListener
    	{
     
    		@Override
    		public void actionPerformed(ActionEvent e) 
    		{
    			try{
     
    				if(e.getSource() == view.addBtn)
    				{
    					//sends button and textField to model class
    					//to handle calculations
    					model.set(view.addBtn, view.textFeild);
     
    					//sets JTextFeild the sum from model.set
    					view.setTextValue(model.getSum());
    				}
    				else if(e.getSource() == view.subtractBtn)
    				{
    					model.set(view.subtractBtn, view.textFeild);
     
    					view.setTextValue(model.getSum());
    				}
    				else if(e.getSource() == view.divideBtn)
    				{
    					model.set(view.divideBtn, view.textFeild);
     
    					view.setTextValue(model.getSum());
    				}
    				else if(e.getSource() == view.multiplyBtn)
    				{
    					model.set(view.multiplyBtn, view.textFeild);
     
    					view.setTextValue(model.getSum());
    				}
    				else if(e.getSource() == view.equalsBtn)
    				{
    					model.set(view.equalsBtn, view.textFeild);
     
    					view.setTextValue(model.getSum());
    				}
    				else if(e.getSource() == view.resetBtn)
    				{
    					model.set(view.resetBtn, view.textFeild);
     
    					view.setTextValue(model.getSum());
    				}
    				//now handing number buttons
    				else if(e.getSource() == view.oneBtn)
    				{
    					model.setNumber(1);
    					view.setTextValue(1);
     
    				}
    				else if(e.getSource() == view.twoBtn)
    				{
    					model.setNumber(2);
    					view.setTextValue(2);
     
    				}
    				else if(e.getSource() == view.threeBtn)
    				{
    					model.setNumber(3);
    					view.setTextValue(3);
    				}
    				else if(e.getSource() == view.fourBtn)
    				{
    					model.setNumber(4);
    					view.setTextValue(4);
    				}
    				else if(e.getSource() == view.fiveBtn)
    				{
    					model.setNumber(5);
    					view.setTextValue(5);
    				}
    				else if(e.getSource() == view.sixBtn)
    				{
    					model.setNumber(6);
    					view.setTextValue(6);
    				}
    				else if(e.getSource() == view.sevenBtn)
    				{
    					model.setNumber(7);
    					view.setTextValue(7);
    				}
    				else if(e.getSource() == view.eightBtn)
    				{
    					model.setNumber(8);
    					view.setTextValue(8);
    				}
    				else if(e.getSource() == view.nineBtn)
    				{
    					model.setNumber(9);
    					view.setTextValue(9);
    				}
    			}catch(Exception ex)
    			{
    				System.out.println("There was an ERROR! "+ex);
     
    			}
     
    		}
     
     
    	}
    }
    main:
    package calculator.MVC;
     
    public class CalculatorMain {
     
    	public static void main(String[] args) 
    	{
    		CalculatorModel model = new CalculatorModel();
    		CalculatorView view = new CalculatorView();
     
    		new CalculatorController(model,view);
    	}
     
    }


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: MVC Calculator:

    I appreciate the vote of confidence, but don't limit yourself to my opinions and inputs. There are many here more talented and experienced than I at many things Java and at programming in general.

    This is an interesting study that could demonstrate a number of things as you complete it and experiment with 'improving' it. Points to think about:

    It departs from strict MVC somewhat in that the View can't stand on its own. Said differently, replacing the View above with another would be more complicated than it should be if done correctly. One of the early MVC tutorials I did to demonstrate a more strict separation of the MVC parts was a much simpler calculator that accepted two numbers and an operator and then provided a result. The interface was first console only and then converted to a GUI by simply substituting the console View with the GUI View. It was that simple.

    As I mentioned would be common, there's no use of the EDT, so you should add that, experiment with which elements should be on the EDT, which shouldn't, and how to accomplish that.

    A full-blown calculator app is a good study in how a strict MVC application can be improved. After typing the long chain of if() statements in a Controller several times, one can't help but thinking, "There's got to be a better way!" Those better ways include: using anonymous action listeners on each GUI element that has a corresponding action, Observer/Observable, EventBus, and probably some others I don't know yet. One could argue that all of those variations wander from strict MVC, but so what? The goal is to achieve a design that can be easily reused, modified, and maintained, not one that strictly adheres to a book's definition of a good practice.

    As you continue, view your work on this app as a study tool, not a calculator that you want to finish and sell or show to all your friends. Build several variations of it: ConsoleCalculator, AnonymousListenerCalculator, ObserverCalculator, EventBusCalculator, etc., and strive to learn as much as you can from each variation. Get each variation mostly 'working', but it's not critical that each be completely finished.

    Keep coding, and good luck!

  3. #3
    Member
    Join Date
    Apr 2014
    Posts
    219
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: MVC Calculator:

    @GregBrandon

    Yes I was wondering that as I wrote several else if statements. Once I get the MVC down I will move on. I about narrowed down the issue but it is still doing a few funny things.

    As always thanks for the advice.

  4. #4
    Member
    Join Date
    Apr 2014
    Posts
    219
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: MVC Calculator:

    I have narrowed down the issue by writing println statements and something odd is happening. The '+' operator is working in the switch statement but the others are not. However in the println statements in each case statement are confirming they are getting the message. For example if I try to to 8 X 8, the println statement will output "The char is: X and the int is: 8" but the sum will stay 0. With '+' operator it outputs: "The char is: + and the int is: 8" "The sum is 16 the number is 8"...

    Therefore my only hang up is the switch statement and I cannot figure out why. I even decided to do a fall through switch statement but it didn't work as expected. This code is below:

    package calculator.MVC;
     
    import javax.swing.JButton;
    import javax.swing.JTextField;
     
    public class CalculatorModel
    {
    	private int sum;
    	private int number;
    	private char opt;
     
    	public CalculatorModel()
    	{
    		sum = 0;
    		number = 0;
    	}
     
    	public void set(JButton idenifier, JTextField number)
    	{
    		//this will receive '+' '-' '/' '*' etc
    		opt = idenifier.getText().charAt(0);
     
    		//getting value from JTextField and setting it as a integer
    		this.number = Integer.parseInt(number.getText());
     
    		//for testing
    		System.out.println("The char is: "+opt+" and the int is: "+this.number);
     
    		calculate(opt);
    	}
     
    	public void setNumber(int number)
    	{
    		this.number = number;
    	}
     
    	public int getSum() {
    		return sum;
    	}
     
    	private void setSum(int sum) 
    	{
    		this.sum = sum;
    	}
     
    	void calculate(char sign)
    	{
    		switch(sign)
    		{
    		case '+':
    			sum += number; 
    			setSum(sum);
    			System.out.println("The sum is "+getSum()+" the number is "+number);
    			break;
     
    		case '-':
    			sum -= number;
    			setSum(sum);
    			System.out.println("The sum is "+getSum()+" the number is "+number);
    			break;
     
    		case '/':
    			sum/= number;
    			setSum(sum);
    			System.out.println("The sum is "+getSum()+" the number is "+number);
    			break;
     
    		case 'X':
    			sum *= number;
    			setSum(sum);
    			System.out.println("The sum is "+getSum()+" the number is "+number);
    			break;
     
    		case '=':
    			number=getSum();
    			System.out.println("The sum is "+getSum());
    			break;
     
    		case 'C':
    			opt = 0;
    			number = 0;
    			sum = 0;
    			setSum(sum);
    			break;
    			default: 
    		}
    	}
    }


    --- Update ---

    OK!!!! I figured it out.... On how to tackle it has be scratching my head.
    case 'X':
    			sum *= number;
    			setSum(sum);
    			System.out.println("The sum is "+getSum()+" the number is "+number);
    			break;

    The sum is set to 0 in the constructor, therefore 0 times anything is naturally 0, so there is my issue. But I am only sending in a number and mathematical operator, which also explains why addition worked so easily.

  5. #5
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: MVC Calculator:

    Discovery is a marvelous and effective teacher. Keep at it.

  6. #6
    Member
    Join Date
    Apr 2014
    Posts
    219
    Thanks
    8
    Thanked 2 Times in 2 Posts

    Default Re: MVC Calculator:

    It bugged me all day at work and it just clicked. It was so simple I felt pretty dumb for not thinking of it sooner. It kinda feels like a patch to a poor thought out plan but it is fully functioning.

    public void set(JButton idenifier, JTextField number)
    	{
    		//this will receive '+' '-' '/' '*' etc
    		opt = idenifier.getText().charAt(0);
     
    		//getting value from JTextField and setting it as a integer
    		this.number = Integer.parseInt(number.getText());
     
    		//for testing
    		System.out.println("The char is: "+opt+" and the int is: "+this.number);
     
    		count++;
    		if(count==1)//getting the first number
    		{
    		num1 = this.number;
    		//System.out.println("num1 is: "+num1);
    		}
    		if(count==2) //getting the second number
    		{
    		num2= this.number; 
     
    			calculate(opt,num1,num2); //sending the sign and both numbers to method
    			//System.out.println("num2 is: "+num2);
     
    		count=0;//resetting count back to zero
    		}

    Thanks GregBrannon for the recommendation and thanks Norm for the advice so many times about the println statements. Now I am going to redo the whole project with a better plan.

Similar Threads

  1. Java mvc
    By Prexstar in forum What's Wrong With My Code?
    Replies: 1
    Last Post: July 25th, 2013, 08:38 AM
  2. Store numbers in mvc Calculator java
    By Spanky13 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: February 25th, 2013, 08:24 PM
  3. Spring MVC
    By BALUBALU in forum Web Frameworks
    Replies: 3
    Last Post: October 10th, 2012, 08:54 AM
  4. MVC with MouseListener
    By horvath62 in forum Java Theory & Questions
    Replies: 2
    Last Post: June 3rd, 2012, 09:26 AM
  5. MVC
    By systech44 in forum Web Frameworks
    Replies: 1
    Last Post: December 9th, 2009, 03:46 AM