[TuT] Making a Calculator in GUI.

Discussion in 'Programming General' started by Fate1, Jan 3, 2008.

Thread Status:
Not open for further replies.
[TuT] Making a Calculator in GUI.
  1. Unread #1 - Jan 3, 2008 at 10:57 PM
  2. Fate1
    Joined:
    Apr 21, 2005
    Posts:
    773
    Referrals:
    2
    Sythe Gold:
    5

    Fate1 Apprentice
    Banned

    [TuT] Making a Calculator in GUI.

    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.

    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..

    This tutorials is 100% by me and the assign method is by the nice guy at sourceworld.com

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

    ~Fate
     
  3. Unread #2 - Aug 26, 2008 at 12:57 AM
  4. mastry_whts
    Referrals:
    0

    mastry_whts Guest

    [TuT] Making a Calculator in GUI.

    ok ur program is very nice but
    u can implement the calculator program in without grid layout and without applets.
    ok
    byeeeeeeee=|
     
  5. Unread #3 - Oct 11, 2008 at 8:17 PM
  6. BJBaller
    Joined:
    Aug 2, 2007
    Posts:
    110
    Referrals:
    0
    Sythe Gold:
    0

    BJBaller Active Member

    [TuT] Making a Calculator in GUI.

    This seems like a good tutorial, Imaginary +1 for you.
     
  7. Unread #4 - Nov 10, 2008 at 4:21 AM
  8. mbahsomo
    Referrals:
    0

    mbahsomo Guest

    [TuT] Making a Calculator in GUI.

    sorry i from Indonesia [newbie in here]
    good article
    i have to
    file name MiniCalculator.java
    Code:
    import javax.swing.*; 
    import java.awt.*; 
    import java.awt.event.*; 
    import java.applet.*; 
    
    public class MiniCalculator extends Applet{ 
       private JPanel panelAtas=new JPanel(); 
       private JPanel panelTengah=new JPanel(); 
       private JPanel panelBawah=new JPanel(); 
       private JTextField tampilan=new JTextField(); 
       private JCheckBox pemisahRibuan=new JCheckBox("Pemisah ribuan",true); 
       private JButton[] tombolFungsi={ 
         new JButton("Hapus"),new JButton("Batal"), 
         new JButton("Ulang"),new JButton("^"), 
         new JButton("7"),    new JButton("8"), 
         new JButton("9"),    new JButton("*"), 
         new JButton("4"),    new JButton("5"), 
         new JButton("6"),    new JButton("/"), 
         new JButton("1"),    new JButton("2"), 
         new JButton("3"),    new JButton("-"), 
         new JButton("0"),    new JButton("."), 
         new JButton("="),    new JButton("+"),}; 
       private JLabel informasi=new JLabel(" Hendra Himawan @ 2007"); 
       private char operator=' '; 
       private double dataPertama=0.0; 
       private double dataKedua=0.0; 
       private double dataHasil=0.0; 
       private boolean awalKetikan=true; 
       private boolean entryPertama=true; 
       private boolean entryDesimal=false; 
    
       public void mini() { 
      setPanelAtas(); 
      setPanelTengah(); 
      setPanelBawah(); 
      resetNilai(); 
      setLayout(new BorderLayout()); 
      add(panelAtas,BorderLayout.NORTH); 
      add(panelTengah,BorderLayout.CENTER); 
      add(panelBawah,BorderLayout.SOUTH); 
      show(); 
       } 
    
       private void resetNilai(){ 
      operator=' '; 
      dataPertama=0.0; 
      dataKedua=0.0; 
      dataHasil=0.0; 
      awalKetikan=true; 
      entryPertama=true; 
      entryDesimal=false; 
       } 
    
       private void setPanelAtas(){ 
      pemisahRibuan.setForeground(new Color(0,0,0)); 
      pemisahRibuan.setFont(new Font("arial",Font.PLAIN,11)); 
      tampilan.setEnabled(false); 
      tampilan.setHorizontalAlignment(JTextField.RIGHT); 
      tampilan.setFont(new Font("arial",Font.BOLD,15)); 
      panelAtas.setLayout(new BorderLayout()); 
      panelAtas.add(tampilan,BorderLayout.CENTER); 
      panelAtas.add(pemisahRibuan,BorderLayout.SOUTH); 
       } 
    
       private void setPanelTengah(){ 
      panelTengah.setLayout(new GridLayout(5,4)); 
      for (int i=0;i<5*4;i++){ 
        tombolFungsi[i].addActionListener(new ActionListener() { 
       public void actionPerformed(ActionEvent e) { 
        tombolFungsiactionPerformed(e); 
         } 
        }); 
        tombolFungsi[i].setFont(new Font("arial",Font.BOLD,11)); 
        panelTengah.add(tombolFungsi[i]); 
      } 
       } 
    
       private void setPanelBawah(){ 
      informasi.setFont(new Font("arial",Font.BOLD+Font.ITALIC,11)); 
      informasi.setForeground(Color.red); 
      panelBawah.setLayout(new BorderLayout()); 
      panelBawah.add(informasi,BorderLayout.WEST); 
      panelBawah.add(new JPanel(),BorderLayout.EAST); 
       } 
    
       private String pisahkan(StringBuffer data){ 
      String temp=data.toString(); 
      if (data.length()>3){ 
        temp=data.substring(data.length()-3); 
        data.delete(data.length()-3,data.length()); 
        temp=pisahkan(data)+','+temp.toString(); 
      } 
      return(temp); 
       } 
    
       private String pisahkanRibuan(double data){ 
      String string=Double.toString(data); 
      int titik=string.indexOf('.'); 
      String pecahan=string.substring(titik); 
      long bulat=new Double(dataHasil).longValue(); 
      string=Long.toString(bulat); 
      string=pisahkan(new StringBuffer(string)); 
      return(string+pecahan); 
       } 
    
       private void hapusKarakter(){ 
      if (tampilan.getText().length()>0){ 
        StringBuffer data=new StringBuffer(tampilan.getText()); 
        char terakhir=data.charAt(data.length()-1); 
        if (terakhir=='.') 
       entryDesimal=false; 
        data.deleteCharAt(data.length()-1); 
        tampilan.setText(data.toString()); 
      } 
       } 
    
       private void batalkanData(){ 
      if (entryPertama) 
        dataPertama=0.0; 
      else 
        dataKedua=0.0; 
      tampilan.setText(""); 
       } 
    
       private void updateData(int index){ 
      if (awalKetikan) 
        tampilan.setText(""); 
      String label=tombolFungsi[index].getLabel(); 
      char karakter=label.charAt(0); 
      StringBuffer data=new StringBuffer(tampilan.getText()); 
      tampilan.setText(data.toString()+karakter); 
      awalKetikan=false; 
       } 
    
       private void updateOperator(int index){ 
      if (entryPertama){ 
        StringBuffer data=new StringBuffer(tampilan.getText()); 
        dataPertama=Double.parseDouble(data.toString()); 
      } 
      String label=tombolFungsi[index].getLabel(); 
      operator=label.charAt(0); 
      entryPertama=false; 
      awalKetikan=true; 
       } 
    
       private void prosesPerhitungan(){ 
      StringBuffer data=new StringBuffer(tampilan.getText()); 
      dataKedua=Double.parseDouble(data.toString()); 
      switch(operator){ 
        case '+' : dataHasil = dataPertama + dataKedua;break; 
        case '-' : dataHasil = dataPertama - dataKedua;break; 
        case '*' : dataHasil = dataPertama * dataKedua;break; 
        case '/' : dataHasil = dataPertama / dataKedua;break; 
        case '^' : dataHasil = Math.pow(dataPertama,dataKedua); 
      } 
    
      if (pemisahRibuan.isSelected()) 
        tampilan.setText(pisahkanRibuan(dataHasil)); 
      else 
        tampilan.setText(Double.toString(dataHasil)); 
      entryPertama=true; 
      awalKetikan=true; 
       } 
    
       private void tambahTandaDesimal(){ 
      if (!entryDesimal && !awalKetikan){ 
        entryDesimal=true; 
        StringBuffer data=new StringBuffer(tampilan.getText()); 
        tampilan.setText(data.toString()+'.'); 
      } 
       } 
    
       public void tombolFungsiactionPerformed(ActionEvent event){ 
      Object objek=event.getSource(); 
      int lokasi=0; 
      for (;lokasi<20;lokasi++) 
        if (objek==tombolFungsi[lokasi]) 
       break; 
      switch(lokasi){ 
        case  0 : hapusKarakter();break; 
        case  1 : batalkanData();break; 
        case  2 : resetNilai();tampilan.setText("");break; 
        case 16 : ; 
        case 12 : ; 
        case 13 : ; 
        case 14 : ; 
        case  8 : ; 
        case  9 : ; 
        case 10 : ; 
        case  4 : ; 
        case  5 : ; 
        case  6 : updateData(lokasi);break; 
        case  3 : ; 
        case  7 : ; 
        case 11 : ; 
        case 15 : ; 
        case 19 : updateOperator(lokasi);break; 
        case 18 : prosesPerhitungan();break; 
        case 17 : tambahTandaDesimal();break; 
      } 
       } 
       
       public void init() { 
      mini(); 
       } 
    }
    create html file write this code
    Code:
    <HTML> 
    <HEAD> 
      <TITLE></TITLE> 
    </HEAD> 
    <BODY> 
      <APPLET CODE="MiniCalculator.class" WIDTH=300 HEIGHT=200></APPLET> 
    </BODY> 
    </HTML>
     
< screen shot taker | Need help chosing a program... Discuss the best program. >

Users viewing this thread
1 guest
Thread Status:
Not open for further replies.


 
 
Adblock breaks this site