Results 1 to 7 of 7
  1. #1
    realahmed8 is offline Member
    Join Date
    Jun 2008
    Posts
    13
    Rep Power
    0

    Question Need little Help In Calculater Implementation..

    I need little help in adding Sin & Cos functions to my calculater , and also in Layout (need textfield to be on the top), so please help me if you can..
    that's my code:

    Java Code:
    package javaapplication3;
    
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import javax.swing.*;
    //import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JApplet;
    import java.lang.Math.*;
    
    public class Calculator3 extends JApplet implements ActionListener
    {
    
    /**************************
        Data Members
    ***************************/
    
    	private	JTextField	JPanel;		//To accept user input and display result
    	private	JButton		JButton0,	//This JButton to pass 0 to JPanel
    				JButton1,	//This JButton to pass 1 to JPanel
    				JButton2,	//This JButton to pass 2 to JPanel
    				JButton3,	//This JButton to pass 3 to JPanel
    				JButton4,	//This JButton to pass 4 to JPanel
    				JButton5,	//This JButton to pass 5 to JPanel
    				JButton6,	//This JButton to pass 6 to JPanel
    				JButton7,	//This JButton to pass 7 to JPanel
    				JButton8,	//This JButton to pass 8 to JPanel
    				JButton9,	//This JButton to pass 9 to JPanel
    				JButtonDiv,	//This JButton operate division
    				JButtonMul,	//This JButton operate multiplication
    				JButtonAdd,	//This JButton operate addition
    				JButtonSub,	//This JButton opearte subtraction
    				JButtonAss,	//This JButton return result
    				JButtonOpar,	//This JButton call open parentheses
    				JButtonCpar,	//This JButton call close parentheses
    				JButtonPoint,	//This JButton to pass . to JPanel
    				JButtonClear;	//This JButton clear JPanel
                  private JButton   JButtonSin;	//This JButton clear JPanel
                  private JButton   JButtonCos;
    	      private int	Flag,		//Record the state after calculating
    				Err_lve;	//State the error level
    
    
    /*************************
        Initialize similar like Constructor, that is use for JApplet
    **************************/
    
    	//public void init()
    	{
    		//setBackground(Color.white);	//Set white backgroud
    		
                JPanel = new JTextField();
                
    		//JPanel.setBounds( 20, 20, 165, 25);
    		add(JPanel);
                    JPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
              
                    setLayout(new GridLayout(5, 5, 5, 5));
    		resize(205, 210);
    
    		Flag = 0;
    		Err_lve = 0;
    
    		
    		JButton0 = new JButton("0");
    		//JButton0.setBounds (20, 160, 25, 25);
    		add(JButton0);
    		JButton1 = new JButton("1");
    		//JButton1.setBounds (20, 125, 25, 25);
    		add(JButton1);
    		JButton2 = new JButton("2");
    		//JButton2.setBounds (55, 125, 25, 25);
    		add(JButton2);
    		JButton3 = new JButton("3");
    		//JButton3.setBounds (90, 125, 25, 25);
    		add(JButton3);
    		JButton4 = new JButton("4");
    		//JButton4.setBounds (20, 90, 25, 25);
    		add(JButton4);
    		JButton5 = new JButton("5");
    		//JButton5.setBounds (55, 90, 25, 25);
    		add(JButton5);
    		JButton6 = new JButton("6");
    		//JButton6.setBounds (90, 90, 25, 25);
    		add(JButton6);
    		JButton7 = new JButton("7");
    		//JButton7.setBounds (20, 55, 25, 25);
    		add(JButton7);
    		JButton8 = new JButton("8");
    		//JButton8.setBounds (55, 55, 25, 25);
    		add(JButton8);
    		JButton9 = new JButton("9");
    		//JButton9.setBounds (90, 55, 25, 25);
    		add(JButton9);
    		JButtonDiv = new JButton("/");
    		//JButtonDiv.setBounds (160, 90, 25, 25);
    		add(JButtonDiv);
    		JButtonMul = new JButton("*");
    		//JButtonMul.setBounds (125, 90, 25, 25);
    		add(JButtonMul);
    		JButtonAdd = new JButton("+");
    		//JButtonAdd.setBounds (125, 55, 25, 25);
    		add(JButtonAdd);
    		JButtonSub = new JButton("-");
    		//JButtonSub.setBounds (160, 55, 25, 25);
    		add(JButtonSub);
    		JButtonAss = new JButton("=");
    		//JButtonAss.setBounds (90, 160, 25, 25);
    		add(JButtonAss);
    		JButtonOpar = new JButton("(");
    		//JButtonOpar.setBounds (125, 125, 25, 25);
    		add(JButtonOpar);
    		JButtonCpar = new JButton(")");
    		//JButtonCpar.setBounds (160, 125, 25, 25);
    		add(JButtonCpar);
    		JButtonPoint = new JButton(".");
    		//JButtonPoint.setBounds (55, 160, 25, 25);
    		add(JButtonPoint);
    		JButtonClear = new JButton("Clear");
    		//JButtonClear.setBounds (125, 160, 60, 25);
    		add(JButtonClear);
                  	JButtonSin = new JButton("S");
    		//JButtonAdd.setBounds (125, 55, 25, 25);
    		add(JButtonSin);
                  	JButtonCos = new JButton("Cos");
    		//JButtonAdd.setBounds (125, 55, 25, 25);
    		add(JButtonCos);                
                    
                    
    		JPanel.addActionListener(this);
    		JButton0.addActionListener(this);
    		JButton1.addActionListener(this);
    		JButton2.addActionListener(this);
    		JButton3.addActionListener(this);
    		JButton4.addActionListener(this);
    		JButton5.addActionListener(this);
    		JButton6.addActionListener(this);
    		JButton7.addActionListener(this);
    		JButton8.addActionListener(this);
    		JButton9.addActionListener(this);
    		JButtonDiv.addActionListener(this);
    		JButtonMul.addActionListener(this);
    		JButtonAdd.addActionListener(this);
    		JButtonSub.addActionListener(this);
    		JButtonAss.addActionListener(this);
    		JButtonOpar.addActionListener(this);
    		JButtonCpar.addActionListener(this);
    		JButtonPoint.addActionListener(this);
    		JButtonClear.addActionListener(this);
                    JButtonSin.addActionListener(this);
                    JButtonCos.addActionListener(this);
    	}
    
    
    	/*
    	Method:		paint
    	Purpose:	Draw the outline of calculator *(this method can auto. draw when develop JApplet, but it isn't JApplet's method)
    	Parameters:	Graphics
    	Returns:	None
    	*/
    
    	/*public void paint(Graphics graphic)
    	{
    		graphic.setColor(Color.yellow);
    		graphic.drawRoundRect(0, 0, 190, 195, 15, 15);
    		graphic.setColor(Color.lightGray);
    		graphic.drawRoundRect(1, 1, 191, 196, 15, 15);
    		graphic.drawRoundRect(2, 2, 192, 197, 15, 15);
    		graphic.drawRoundRect(3, 3, 193, 198, 15, 15);
    		graphic.drawRoundRect(4, 4, 194, 199, 15, 15);
    		graphic.setColor(Color.black);
    		graphic.fillRoundRect(5, 5, 195, 200, 15, 15);
    		graphic.setColor(Color.green);
    		graphic.drawRoundRect(5, 5, 195, 200, 15, 15);
    		graphic.setColor(Color.yellow);
    		graphic.drawString("Data Structure", 45, 200);
    	}
    */
    
    	/*
    	Method:		actionPerformed
    	Purpose:	Event-handling
    	Parameters:	Action event
    	Returns:	None
    	*/
    
    	public void actionPerformed(ActionEvent event)
    	{
    		if (event.getSource() instanceof JButton)
    		{
    			JButton clickedJButton = (JButton) event.getSource();
    			if (clickedJButton == JButtonClear)
    			{
    				ClearJPanel();
    				Flag = 0;
    			}
    				else if (clickedJButton == JButtonAss)
    				{
    					Err_lve = 0;
    					Compute();
    					Flag = 1;
    				}
    					else
    					{
    						if (Flag == 1)
    						{
    							ClearJPanel();	//clear JPanel after calculation
    							Flag = 0;
    						}
    						DisplayEx(clickedJButton);
    					}
    		}
    		else
    		{
    			Err_lve = 0;
    			Compute();
    			Flag = 1;
    		}
    	}
    
    
    	/*
    	Method:		ClearJPanel
    	Purpose:	Clear JPanel JTextField objects
    	Parameters:	None
    	Returns:	None
    	*/
    
    	private void ClearJPanel()
    	{
    		JPanel.setText("");
    	}
    
    
    	/*
    	Method:		DisplayEx
    	Purpose:	Display the whole expression that the user enters
    	Parameters:	clickedJButton
    	Returns:	None
    	*/
    
    	private void DisplayEx(JButton ClickedJButton)
    	{
    		String tmpstr;
    		tmpstr = JPanel.getText();
    		if (ClickedJButton == JButton0)	JPanel.setText(tmpstr+"0");
    		if (ClickedJButton == JButton1)	JPanel.setText(tmpstr+"1");
    		if (ClickedJButton == JButton2)	JPanel.setText(tmpstr+"2");
    		if (ClickedJButton == JButton3)	JPanel.setText(tmpstr+"3");
    		if (ClickedJButton == JButton4)	JPanel.setText(tmpstr+"4");
    		if (ClickedJButton == JButton5)	JPanel.setText(tmpstr+"5");
    		if (ClickedJButton == JButton6)	JPanel.setText(tmpstr+"6");
    		if (ClickedJButton == JButton7)	JPanel.setText(tmpstr+"7");
    		if (ClickedJButton == JButton8)	JPanel.setText(tmpstr+"8");
    		if (ClickedJButton == JButton9)	JPanel.setText(tmpstr+"9");
    		if (ClickedJButton == JButtonDiv)	JPanel.setText(tmpstr+"/");
    		if (ClickedJButton == JButtonMul)	JPanel.setText(tmpstr+"*");
    		if (ClickedJButton == JButtonAdd)	JPanel.setText(tmpstr+"+");
    		if (ClickedJButton == JButtonSub)	JPanel.setText(tmpstr+"-");
    		if (ClickedJButton == JButtonOpar)JPanel.setText(tmpstr+"(");
    		if (ClickedJButton == JButtonCpar)JPanel.setText(tmpstr+")");
    		if(ClickedJButton == JButtonPoint)JPanel.setText(tmpstr+".");
                    if (ClickedJButton == JButtonSin)	JPanel.setText(tmpstr+"S");
                    if (ClickedJButton == JButtonCos)	JPanel.setText(tmpstr+"Cos ");
            }
    
    
    	/*
    	Method:		Compute
    	Purpose:	Calculate the expression and shown the result, when the user hit return key or "=" JButton.
    	Parameters:	The whole expression
    	Returns:	None
    	*/
    
    	private void Compute()
    	{
    		String	Tmpstr, Result="";
    		char	ch;
    		int	i, no_of_char,
    			no_of_par = 0;
    
    		Tmpstr		= JPanel.getText();
    		no_of_char	= Tmpstr.length();
    
    		//Expression brief checking
    		for (i = 0; i < no_of_char; i++)
    		{
    			ch = Tmpstr.charAt(i);
    			if (ch == ')') no_of_par--;
    			if (no_of_par < 0) Err_lve = 1;
    			if (ch == '(') no_of_par++;
    			if (ch < '(' || ch > '9' || ch == ',') Err_lve = 2;
    			if (ch == '.' && (i+1 < Tmpstr.length()) )
    				for ( int j = i+1; (j < Tmpstr.length()) && ((Character.isDigit(Tmpstr.charAt(j))) || ((Tmpstr.charAt(j))) == '.'); j++ )
    					if (Tmpstr.charAt(j) == '.') Err_lve = 3;
    								//If an operand has more than one point return error
    		}//End of expression brief checking
    
    		if (no_of_par != 0) Err_lve = 1;		//If open and close parentheses do not match return error
    
    		if (Err_lve != 0) Err_msg(Err_lve);		//An error perform to prompt error message
    		else Result = Calculate(Tmpstr);		//No error perform to calculate expression
    		if (Err_lve != 0) Err_msg(Err_lve);		//An error perform to prompt error message
    		else JPanel.setText(Result);			//No error show result
    	}
    
    
    	/*
    	Method:		Calculate
    	Purpose:	Implement the expression
    	Parameters:	Expression
    	Returns:	None
    	*/
    
    	private String Calculate(String expression)
    	{
    		String	result = expression, f_operand, r_operand;
    		char	cha;
    		int	index, f_index, r_index,
    			no_of_cha = result.length(),
    			no_of_pare = 0, pare_match = 0, op_index = 0, cp_index = 0;
    
    	    if (Err_lve == 0)
    	    {
    		//Checking Parentheses
    		for (index = 0; index < no_of_cha; index++)
    		{
    			cha = result.charAt(index);
    
    			if (cha == '(')
    			{
    				if (pare_match == 0)	op_index = index;
    				pare_match ++;
    				no_of_pare ++;
    			}
    
    			if (cha == ')')
    			{
    				pare_match --;
    				if (pare_match == 0)	cp_index = index;
    			}
    		}//End of checking Parentheses
    
    		if (op_index+1 == cp_index) Err_lve = 3;
    
    		//Recursive Calculate, when parentheses existed
    		if (Err_lve == 0 && no_of_pare > 0)
    		{
    		if ((op_index == 0) && (cp_index == (no_of_cha - 1)) && (op_index != cp_index)) result = Calculate(result.substring(op_index + 1, cp_index));
    			else if (op_index == 0 && cp_index > 0)
    			{
    				if ( (Character.isDigit(result.charAt(cp_index+1))) ) Err_lve = 3;
    				else
    				{
    					result = Calculate(result.substring(op_index + 1, cp_index)) + result.substring(cp_index + 1);
    					no_of_pare--;
    					while(no_of_pare != 0)
    					{
    						result = Calculate(result);
    						no_of_pare--;
    					}
    				}
    			}
    				else if ((op_index > 0) && (cp_index > 0) && (cp_index != no_of_cha -1))
    				{
    					if ( (Character.isDigit(result.charAt(cp_index+1))) || (Character.isDigit(result.charAt(op_index-1))) ) Err_lve = 3;
    					else
    					{
    						result = result.substring(0, op_index) + Calculate(result.substring(op_index +1, cp_index)) + result.substring(cp_index +1);
    						no_of_pare--;
    						while(no_of_pare != 0)
    						{
    							result = Calculate(result);
    							no_of_pare--;
    						}
    					}
    				}
    					else if (cp_index == no_of_cha -1 && op_index > 0)
    					{
    						if ( (Character.isDigit(result.charAt(op_index-1))) ) Err_lve = 3;
    						else
    						{
    							result = result.substring(0, op_index) + Calculate(result.substring(op_index + 1, cp_index));
    							no_of_pare--;
    							while(no_of_pare != 0)
    							{
    								result = Calculate(result);
    								no_of_pare--;
    							}
    						}
    					}
    		}//End of recursive Calculate statement
    
    
    		//Implement algorithm
    		if (no_of_pare == 0 && Err_lve == 0)
    		{
    			if ( (!(Character.isDigit(result.charAt(0))) && (result.charAt(0) != '-')) || !(Character.isDigit(result.charAt(result.length()-1))) ) Err_lve = 3;
    
    			//Implement multiply and divide first
    			for (index = 0; index < result.length() && (Err_lve == 0); index++)
    			{
    				cha = result.charAt(index);
    
    				if (cha == '*' || cha == '/')
    				{
    					if ( !(Character.isDigit(result.charAt(index-1))) || ( !(Character.isDigit(result.charAt(index+1))) && (result.charAt(index+1) != '-') ) ) Err_lve = 3;
    					if (result.charAt(index+1) == '-')
    						if ( !(Character.isDigit(result.charAt(index+2))) ) Err_lve = 3;
    					if (Err_lve == 0)
    					{
    						f_index = index - 1;
    
    						if (f_index > 2)
    							if ( ((result.charAt(f_index-1)) == '-') && ((result.charAt(f_index-2)) == 'E') )
    								f_index = f_index - 2;
    
    						while ( (f_index > 0) && ((Character.isDigit(result.charAt(f_index-1))) || ((result.charAt(f_index-1)) == '.') || ((result.charAt(f_index-1)) == 'E')) )
    						{
    							f_index--;
    						}
    						if (f_index ==1)
    							if ((result.charAt(f_index-1)) == '-')
    								f_index--;
    						if (f_index > 2)
    							if ( ((result.charAt(f_index-1)) == '-') && !(Character.isDigit(result.charAt(f_index-2))) )
    								f_index--;
    						f_operand = result.substring(f_index, index);
    
    						r_index = index + 1;
    						while ( (r_index < result.length()-1) && ((Character.isDigit(result.charAt(r_index+1))) || ((result.charAt(r_index+1)) == '.') || ((result.charAt(r_index+1)) == 'E')) )
    						{
    							r_index++;
    							if (r_index < result.length()-2)
    								if ( ((result.charAt(r_index)) == 'E') && ((result.charAt(r_index+1)) == '-') )
    									r_index++;
    						}
    						r_operand = result.substring(index+1, r_index+1);
    
    						if ( (f_index != 0) && (r_index != result.length()-1) )
    						{
    						    if (Algorithm(cha, f_operand, r_operand).charAt(0) == 'N') Err_lve = 4;				//If an answer is not a number return error
    						    if (Algorithm(cha, f_operand, r_operand).charAt(0) == 'I') Err_lve = 5;				//If an answer is Infinity return error
    
    						    result = result.substring(0, f_index) + Algorithm(cha, f_operand, r_operand) + result.substring(r_index+1);
    						    index = 0;
    						}
    							else if ( (f_index == 0) && (r_index == result.length()-1) )
    							{
    							    if (Algorithm(cha, f_operand, r_operand).charAt(0) == 'N') Err_lve = 4;			//If an answer is not a number return error
    							    if (Algorithm(cha, f_operand, r_operand).charAt(0) == 'I') Err_lve = 5;			//If an answer is Infinity return error
    
    							    result = Algorithm(cha, f_operand, r_operand);
    							}
    								else if (f_index == 0)
    								{
    								    if (Algorithm(cha, f_operand, r_operand).charAt(0) == 'N') Err_lve = 4;		//If an answer is not a number return error
    								    if (Algorithm(cha, f_operand, r_operand).charAt(0) == 'I') Err_lve = 5;		//If an answer is Infinity return error
    
    								    result = Algorithm(cha, f_operand, r_operand) + result.substring(r_index+1);
    								    index = 0;
    								}
    									else if (r_index == result.length()-1)
    									{
    									    if (Algorithm(cha, f_operand, r_operand).charAt(0) == 'N') Err_lve = 4;	//If an answer is not a number return error
    									    if (Algorithm(cha, f_operand, r_operand).charAt(0) == 'I') Err_lve = 5;	//If an answer is Infinity return error
    
    									    result = result.substring(0, f_index) + Algorithm(cha, f_operand, r_operand);
    									}
    					}
    				}
    			}//End of implement multiply and divide
    
    
    			//Implement add and subtract
    			for (index = 0; index < result.length() && (Err_lve == 0); index++)
    			{
    				if (index == 0 && result.charAt(index) == '-') index = 1;
    
    				if (index > 0)
    					if ( ((result.charAt(index)) == 'E') && ((result.charAt(index+1)) == '-') )
    						index = index + 2;
    
    				cha = result.charAt(index);
    
    				if (cha == '+' || cha == '-')
    				{
    					if ( !(Character.isDigit(result.charAt(index-1))) || ( !(Character.isDigit(result.charAt(index+1))) && (result.charAt(index+1) != '-') ) ) Err_lve = 3;
    					if (result.charAt(index+1) == '-')
    						if ( !(Character.isDigit(result.charAt(index+2))) ) Err_lve = 3;
    					if (Err_lve == 0)
    					{
    						f_index = 0;
    						f_operand = result.substring(f_index, index);
    
    						r_index = index + 1;
    						while ( (r_index < result.length()-1) && ((Character.isDigit(result.charAt(r_index+1))) || ((result.charAt(r_index+1)) == '.') || ((result.charAt(r_index+1)) == 'E')) )
    						{
    							r_index++;
    							if (r_index < result.length()-2)
    								if ( ((result.charAt(r_index)) == 'E') && ((result.charAt(r_index+1)) == '-') )
    									r_index++;
    						}
    						r_operand = result.substring(index+1, r_index+1);
    						result = Algorithm(cha, f_operand, r_operand) + result.substring(r_index+1);
    						index = 0;
    					}
    				}
    			}//End of implement add and subtract
    
    		}//End of implement algorithm
    
    	    }
    	    return result;
    	}
    
    
    	/*
    	Method:		Algorithm
    	Purpose:	Implement the simple expression
    	Parameters:	Operator, front value and rear value
    	Returns:	None
    	*/
    
    	private String Algorithm(char Operator, String F_operand, String R_operand)
    	{
    		Double	F, R;
    		double	f, r,
    			ans = 0;
    		String	res;
    
    		F = new Double(F_operand);
    		R = new Double(R_operand);
    		f = F.doubleValue();
    		r = R.doubleValue();
                    //double angle = r * 2.0 * Math.PI/360.0;
                    
    		if (Operator == '+') ans = f + r;
    		if (Operator == '-') ans = f - r;
    		if (Operator == '*') ans = f * r;
    		if (Operator == '/') ans = f / r;
                  //  if (Operator == 'S') ans = Math.sin(angle);
    		res = Double.toString(ans);
    
    		return res;
    	}
    /*private String Algorithm2(String Operator, String Operand)
    	{
        Double F;
        double f=0;
       double answ=0;
        String result;
        F = new Double(Operand);
        double angle = f * 2.0 * Math.PI/360.0;
        if (Operator=="S") answ = Math.sin(angle);
    		result = Double.toString(answ);
    
    		return result;
    }
    */
    	/*
    	Method:		Err_msg
    	Purpose:	Prompt error message
    	Parameters:	Error level
    	Returns:	None
    	*/
    
    	private void Err_msg(int Err_lve)
    	{
    		switch(Err_lve)
    		{
    			case 1:
    				JPanel.setText("Parentheses do not match");
    				break;
    			case 2:
    				JPanel.setText("Invalid input");
    				break;
    			case 3:
    				JPanel.setText("Invalid expression");
    				break;
    			case 4:
    				JPanel.setText("Not a number exist");
    				break;
    			case 5:
    				JPanel.setText("Infinity exist");
    				break;
    			default:
    				JPanel.setText("Unknow error");
    				break;
    		}
    	}
    }
    /*... End of Calculator.java ...*/

  2. #2
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    6

    Default

    Whats the issue? The math class has a .cos() and .sin() function readily available. Just add 2 more buttons to your layout with listeners that work exactly how your other functions work except it takes the parameters and converts to radians, decimals, or uses them as is.
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  3. #3
    realahmed8 is offline Member
    Join Date
    Jun 2008
    Posts
    13
    Rep Power
    0

    Default

    can you please try to add it, i know it needs Math library but it failed to execute well as i need.. i have added two sin & cos buttons with listeners.. seems little problem still..

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    1. What logic are you striving for here? Are you trying to calc sin and cos immediately on pressing the button, or are you striving to create a String in the display and then parse it when the equals button is pressed? Most calculators that I deal with use the former, but I have seen some that use the latter (rarely).

    2. Have you read up on how to use the layout managers available for Swing?

    3. You probably want to separate out your logic from your GUI here, else you will be having an extreme nightmare trying to debug or extend your app.

    4. You can cut out over 50% of the code above by smart use of arrays. This will also make it easier to debug or extend your app.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    For an example of a typical layout that uses arrays, here's a calculator GUI that doesn't have the logic yet:

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JComponent;
    import javax.swing.JTextField;
    
    public class CalculatorGUI
    {
      private JPanel mainPanel = new JPanel();
      private String[][] buttonStrings =
      {
          {"7", "8", "9", "/"},
          {"4", "5", "6", "*"},
          {"1", "2", "3", "-"},
          {"0", ".", "=", "+"}
      };
      private JTextField displayField = new JTextField();
      private StringBuilder displaySB = new StringBuilder();
      private boolean dotEntered = false;
    
      public CalculatorGUI()
      {
        int rows = buttonStrings.length;
        int cols = buttonStrings[0].length;
        JPanel btnPanel = new JPanel(new GridLayout(rows, cols));
        NumberBtnListener numberBtnListener = new NumberBtnListener();
        for (int i = 0; i < buttonStrings.length; i++)
        {
          for (int j = 0; j < buttonStrings[i].length; j++)
          {
            String btnString = buttonStrings[i][j];
            JButton btn = new JButton(btnString);
            btnPanel.add(btn);
            if ("0123456789.".contains(btnString))
            {
              btn.addActionListener(numberBtnListener);
            }
            
          }
        }
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(btnPanel, BorderLayout.CENTER);
        mainPanel.add(displayField, BorderLayout.NORTH);
      }
    
      public JComponent getComponent()
      {
        return mainPanel;
      }
      
      private class NumberBtnListener implements ActionListener
      {
        public void actionPerformed(ActionEvent e)
        {
          String btnString = e.getActionCommand();
          if (btnString.equals("."))
          {
            if (dotEntered)
            {
              return;
            }
            else
            {
              dotEntered = true;
            }
          }
          
          displaySB.append(btnString);
          displayField.setText(displaySB.toString());
        }
      }
    
      private static void createAndShowUI()
      {
        JFrame frame = new JFrame("MyMain");
        frame.getContentPane().add(new CalculatorGUI().getComponent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowUI();
          }
        });
      }
    }

  6. #6
    realahmed8 is offline Member
    Join Date
    Jun 2008
    Posts
    13
    Rep Power
    0

    Default

    my calculator accept long expression with parenthesis that's why the code is long, i know it seems not logical and iam trying to cut and replace..
    it was longer than that..
    if you have alternative code or method that accept expressions with parenthesis please help..
    thank you..

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Yeah, for the logic part (and again, this must go in a different class than the GUI), you should search for tutorials on infix to postfix conversion. A Google search on these terms might help:

    infix postfix notation java stack

    For example have a look at this article on the subject:
    Postfix Notation Mini-Lecture

Similar Threads

  1. VietPad 2.0 (.NET implementation)
    By Java Tip in forum Java Software
    Replies: 0
    Last Post: 04-05-2008, 04:32 PM
  2. Graph DPS and BFS implementation
    By hey in forum New To Java
    Replies: 1
    Last Post: 01-09-2008, 09:19 PM
  3. Help with recursive implementation
    By toby in forum Advanced Java
    Replies: 1
    Last Post: 08-07-2007, 05:57 AM
  4. Help with implementation of the DataSet class
    By silvia in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 05:47 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •