Creating a caclulator using GUI[Java][Beginners]

Discussion in 'Archives' started by Fate1, Mar 4, 2009.

Creating a caclulator using GUI[Java][Beginners]
  1. Unread #1 - Mar 4, 2009 at 2:21 PM
  2. Fate1
    Joined:
    Apr 21, 2005
    Posts:
    773
    Referrals:
    2
    Sythe Gold:
    5

    Fate1 Apprentice
    Banned

    Creating a caclulator using GUI[Java][Beginners]

    This tutorial will show you how to make a Calculator using GUI. It will explain some of the methods used in GUI and how you can use them. I am still a beginner in java so I am just trying to teach you what I know. Any Java gurus notice anything wrong please post and tell me. Or anything to help me improve would be great thanks.

    First you must import the awt, swing and the evnt classes. Open a new document and put this at the top.

    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    Now, you can use methods from the classes to make GUI.

    Next add this.

    Code:
    public class CalcFrame extends JFrame implements ActionListener {
    Make sure when you compile the file the filename is the same as the class name. In this case CalcFrame.java you would save it as.

    Now you have to add Buttons to the calculator such as the numbers 1 - 9,
    the mathematical operators, a text field for the answer to show up at, and also a clear button.
    The method to add buttons is JButton().
    Add this.

    Code:
    	static JTextField answer = new JTextField("0",12);
                 JButton zero = new JButton("0");
    	JButton one = new JButton("1");
    	JButton two = new JButton("2");
    	JButton three = new JButton("3");
    	JButton four = new JButton("4");
    	JButton five = new JButton("5");
    	JButton six = new JButton("6");
    	JButton seven = new JButton("7");
    	JButton eight = new JButton("8");
    	JButton nine = new JButton("9");
    	JButton divide = new JButton("/");
    	JButton multiply = new JButton("*");
    	JButton add = new JButton("+");
    	JButton subtract = new JButton("-");
    	JButton equal = new JButton("="); 
    	JButton dot = new JButton(".");
    	JButton AC = new JButton("AC");
    The JTextField answer = new JTextField("0",12);. That makes a new Text field for where the answer to show up at. The "0" is a string and it displays 0 on the text field. The 12 stands for how big the text field is.

    Now you need some panels to put the buttons on.

    Add this

    Code:
    	Panel p1,p2,p3,p4,p5,p6;
    Than add this

    Code:
        p1 = new Panel();
         	p2 = new Panel();
         	p3 = new Panel();
         	p4 = new Panel();
         	p5 = new Panel();
    Now that we got our panels and buttons, lets start to add them. But first lets set the size and title for the calculator.

    Add

    Code:
    Public CalcFrame() {
    }
    Now in between the '{' and '}' add this
    Code:
        setTitle("Fates Calculator");
         	setSize(300,250);
         	setResizable(false); 
    The setTitle("String") method sets the title obviously. The setSize(Width,Height) sets the size and the setResizable(boolean) method either allows the user to resize the Calculator. In this case we wont let them.

    We also want them to close the program when they push the [X] button. So you must add this.

    Code:
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    This allows the program to close when they push the [X] button.

    Since we made some panels and buttons. We want them to look good don't we? So lets make a layout.

    Code:
         	p1.setLayout(new GridLayout (1, 3, 2, 2) );
    		p2.setLayout(new GridLayout (1, 3, 2, 2) );
    		p3.setLayout(new GridLayout (1, 3, 2, 2) );
    		p4.setLayout(new GridLayout (1, 3, 2, 2) );
    		p5.setLayout(new GridLayout (1, 3, 2, 2) );
    The p1,p2,p3 etc. They are the panels you made already. You then make a new GridLayout. The 1 stands for the number of rows, the 3 stands for the number of columns, then 2 stands for 2 Pixel Horizontal gap in between the buttons and the other 2 stands for 2 Pixel Vertical gap in between the buttons.

    Since we finished that lets add our events to make the buttons work.
    Code:
         	dot.addActionListener(this);
         	equal.addActionListener(this);
         	zero.addActionListener(this);
         	one.addActionListener(this);
         	two.addActionListener(this);
         	three.addActionListener(this);
         	four.addActionListener(this);
         	five.addActionListener(this);
         	six.addActionListener(this);
         	seven.addActionListener(this);
         	eight.addActionListener(this);
         	nine.addActionListener(this);
         	multiply.addActionListener(this);
         	divide.addActionListener(this);
         	add.addActionListener(this);
         	subtract.addActionListener(this);
         	AC.addActionListener(this);
    This allows you to add events for the buttons.

    Also add this

    Code:
      answer.setEditable(false);
    This makes the text field uneditable so the users can't type stuff into it.

    Lets now add the buttonsto the panels.

    Code:
         AC.setForeground(Color.red);
         	p1.add(AC);
         	p2.add(seven);
         	p2.add(eight);
         	p2.add(nine);
         	p2.add(divide);
         	p3.add(four);
         	p3.add(five);
         	p3.add(six);
         	p3.add(multiply);
         	p4.add(one);
         	p4.add(two);
         	p4.add(three);
         	p4.add(subtract);
         	p5.add(zero);
         	p5.add(dot);
           	p5.add(add);
         	p5.add(equal);
    The p1-p5 stand for the panel names. The .add adds the component to that panel. For an example p5.add(add); That adds the '+' button to that panel.

    Now lets set the layout for the all the panels and lets actually now add the panels

    Code:
        setLayout(new GridLayout(6,1));
         	add(answer);
         	add(p1);
         	add(p2);
         	add(p3);
         	add(p4);
         	add(p5);
         	
    We added the buttons to the panels and now we just added the panels to the program. Lets now allow the frame to be visible.

    Code:
      setVisible(true);
    	pack();
    	}
    The pack() method resizes the frame to the right size so everything just fits in it. If it is too small it will make it bigger, or if it is too big it will shrink it.

    If you try to compile it now you will get an error message saying you need the void performedAction(ActionEvent evt) { }.

    Well actually you do so lets add it

    Code:
    public void performedAction(ActionEvent evt) {
    }
    In between the '{' and '}' add this.

    Code:
    Object source = evt.getSource();
    This tells you what the user is clicking or doing.

    Since we have to use the source lets add the mathematical operators and the numbers. This will get them working.

    Code:
    		if (source == add) {
    			number1 = Double.parseDouble(answer.getText());
    			answer.setText("");
    			choice = '+';
    		}
    		if (source == subtract) {
    			number1 = Double.parseDouble(answer.getText());
    			answer.setText("");
    			choice = '-';
    		}
    		if (source == multiply) {
    			number1 = Double.parseDouble(answer.getText());
    			answer.setText("");
    			choice = '*';
    		}
    		if (source == divide) {
    			number1 = Double.parseDouble(answer.getText());
    			answer.setText("");
    			choice = '/';
    		}
    		if (source == zero) {
    			assign("0");
    		} else
    		if (source == one) {
    			assign("1");
    		} else
    		if (source == two) {
    			assign("2");
    		} else
    		if (source == three) {
    			assign("3");
    		} else
    		if (source == four) {
    			assign("4");
    		} else
    		if (source == five) {
    			assign("5");
    		} else
    		if (source == six) {
    			assign("6");
    		} else
    		if (source == seven) {
    			assign("7");
    		} else
    		if (source == eight) {
    			assign("8");
    		} else
    		if (source == nine) {
    			assign("9");
    		}
    Now go back up to the top of your file and add these.

    Code:
    	double number1, number2, result;
    	char choice;
    	static String lastCommand = null;
    Also, we need to add the assign method.

    At the top add this also..

    Code:
    	private static void assign(String no)
            {
             if((answer.getText()).equals("0"))
                answer.setText(no);
              else if(lastCommand == "=")
               {
                answer.setText(no);
                lastCommand = null;
               }
              else
                answer.setText(answer.getText()+no);
             }
    [This method is not by me. I give credits to the guy who wrote it a sourceworld.com. It is very usefull and I thank him.).

    Phew we are almost done!

    Next lets make the mathematical operators work like we want them to do.

    Code:
    	if (source == equal) {
    		number2 = Double.parseDouble(answer.getText());
    		if (choice == '+') {
    			result = number1 + number2;
    			answer.setText("" + result);
    			number1 = 0;
    			number2 = 0;
    		}
    		if (choice == '-') {
    			result = number1 - number2;
    			answer.setText("" + result);
    			number1 = 0;
    			number2 = 0;
    		}
    		if (choice ==  '*') {
    			result = number1 * number2;
    			answer.setText("" + result);
    			number1 = 0;
    			number2 = 0;
    		}
    		if (choice == '/') {
    			result = number1 / number2;
    			answer.setText("" + result);
    			number1 = 0;
    			number2 = 0;
    		}
    	}
    
    We also need to add the Clear button.

    Code:
    		if (source == AC) {
    			answer.setText("0");
    			number1 = 0;
    			number2 = 0;
    		}
    	}
    }
    
    But wait we are not finished yet!

    Now at the bottom of the file add this

    Code:
    public static void main(String[] args) {
    CalcFrame frame = new Frame();
    }
    }
    That actually runs all that code we just wrote..

    If you need any help or questions post here and I will gladly help.



    ~Fate
     
< Looking to buy range or mage pure... | Selling skiller 30 def 12 cb. >

Users viewing this thread
1 guest


 
 
Adblock breaks this site