Java GUI Calculator Tutorial (NEW) Part 3: Adding Components

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

Your code is working perfectly. Thank you for sharing your knowledge.

thisnyper
Автор

what im gonna do if two Jtexfield numbers in the calculator?
how can i command all buttons numbers put to second textfield?:)

-java

crisremiter
Автор

Exception in thread "main"
at
at
Java Result: 1
I dont understand why is this error coming. Its not running 

ANUBHAVG
Автор

Dude help add(numberButtons[i] gbc); the gbc has error help please

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    Syntax error on token "gbc", delete this token

    at
    at

derpking
Автор

So I have written the code, and added extra features to the calculator, I also added comments to make everything clear. There are still a few errors which I dont know how to solve.
1. After doing any equation, ie. 10+20 I get 30, but if I want to do more calculations  ie. subtract 5, the 5 adds to the value 30 (305). How can I correct this?
2. I dont know how to implement the % and <-  button..
anyways enjoy the code..

package calculator;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Calculator extends JPanel implements ActionListener{
    
    VARIABLES    
    private GridBagLayout layout;
    private GridBagConstraints gbc;
    
    private JButton[] numberButtons;
    private JButton[] otherButtons;
        
    private JTextField field;
        
    private double num1, num2, total;
    private int operator;
    
    
    ORDERING BUTTONS
        // [0]=gridx(column),   [1]=gridy(row),  [2]=gridwidth,  [3]=gridheight
       
        //Number buttons
        private int[][] numConstraints = new int[][]{
        {0, 5, 2, 1}, //0
        {0, 4, 1, 1}, //1
        {1, 4, 1, 1}, //2
        {2, 4, 1, 1}, //3
        {0, 3, 1, 1}, //4
        {1, 3, 1, 1}, //5
        {2, 3, 1, 1}, //6
        {0, 2, 1, 1}, //7
        {1, 2, 1, 1}, //8
        {2, 2, 1, 1}, //9 
        };
        
        // [0]=gridx(column),   [1]=gridy(row),  [2]=gridwidth,  [3]=gridheight        
        //Other buttons
        private int[][] otherConstraints = new int[][]{
        {2, 5, 1, 1}, // .
        {4, 4, 1, 2}, // =
        {3, 5, 1, 1}, // +
        {3, 4, 1, 1}, // -
        {3, 3, 1, 1}, // *
        {3, 2, 1, 1}, // '/'
        {2, 1, 1, 1}, // +/-
        {1, 1, 1, 1}, // C
        {4, 2, 1, 1}, // %
        {4, 1, 1, 1}, // √
        {3, 1, 1, 1}, // ^2
        {0, 1, 1, 1}, // ←
        {4, 3, 1, 1}, // 1/x
        };
        
        
    CONSTRUCTORS
    public Calculator(){
        
        //Define Layout
        layout = new GridBagLayout();
        layout.columnWidths = new int[]{60, 60, 60, 60, 60}; //5 button columns and size
        layout.rowHeights = new int[]{60, 60, 60, 60, 60, 60}; //6 button rows and size     
        setLayout(layout);
        
        gbc = new GridBagConstraints();
        
        //Number Buttons display
        numberButtons = new JButton[10];
        
        for(int i=0; i<numberButtons.length; i++){
            numberButtons[i] = new JButton("" + i);
            //allow button to be listened
            
            gbc.gridx = numConstraints[i][0]; //column **ALL THESE ALREADY DEFINED ABOVE**
            gbc.gridy = numConstraints[i][1]; //row
            gbc.gridwidth = numConstraints[i][2]; //width
            gbc.gridheight = numConstraints[i][3]; //height
            gbc.fill = GridBagConstraints.BOTH; //Take complete cell space
            gbc.insets = new Insets(2, 2, 2, 2); //padding
            
            add(numberButtons[i], gbc); //add the buttons
        }
        
        //Other Butttons incl. operators
        otherButtons = new JButton[13];
        otherButtons[0] = new JButton(".");
        otherButtons[1] = new JButton("=");
        otherButtons[2] = new JButton("+");
        otherButtons[3] = new JButton("-");
        otherButtons[4] = new JButton("x");
        otherButtons[5] = new JButton("÷");
        otherButtons[6] = new JButton("±");
        otherButtons[7] = new JButton("C");
        otherButtons[8] = new JButton("%");
        otherButtons[9] = new JButton("√");
        otherButtons[10] = new JButton("^2");
        otherButtons[11] = new JButton("←");
        otherButtons[12] = new JButton("1/x");
        
        
        
        for(int i=0; i<otherButtons.length; i++){
            gbc.gridx = otherConstraints[i][0];
            gbc.gridy = otherConstraints[i][1];
            gbc.gridwidth = otherConstraints[i][2];
            gbc.gridheight = otherConstraints[i][3];
                        
           
            
            add(otherButtons[i], gbc);
            
        }
        
        //Display text field
        field = new JTextField(); //define field
        //set border color to black
        field.setEditable(false); //cannot be edited
        field.setFont(new Font("Arial", Font.PLAIN, 26)); //font style and size
       
        field.setText("0");
        gbc.gridx = 0; //column
        gbc.gridy = 0; //row
        gbc.gridwidth = 5; //width
        gbc.gridheight = 1; //height
        
        add(field, gbc); //add the field
        
        
    }
    
    //Action Events for each button
    public void actionPerformed(ActionEvent e){    //e can be any name
        
        //for number buttons pressed, display to the field
        for(int i=0; i<numberButtons.length; i++){
            if(e.getSource() == numberButtons[i]){
                field.setText(field.getText() + i); //settext=set to field, gettext=get pressed key from i
            }
        }
        
        if(e.getSource() == otherButtons[0] &&    //if current number is 0 and if decimal is
            field.setText(field.getText() + ".");                                  //already added, another decimal cannot be added
        }
        
        if(e.getSource() == otherButtons[6]){   //6 is +/- (change value to positive or negative)
            field.setText("" + (-1 * ); //multiply by negative 1 to change value
        }
        
        if(e.getSource() == otherButtons[7]){   //7 is C (clear)
            field.setText("0"); //if pressed clear everything
        }
        
        if(e.getSource() == otherButtons[2]){    //2 is +
            num1 =
            operator = 2;
            field.setText("");
        }
        
        if(e.getSource() == otherButtons[3]){   //3 is -
            num1 =
            operator = 3;
            field.setText("");
        }
        
        if(e.getSource() == otherButtons[4]){   //4 is *
            num1 =
            operator = 4;
            field.setText("");
        }
        
        if(e.getSource() == otherButtons[5]){   //5 is /
            num1 =
            operator = 5;
            field.setText("");
        }
        
        if(e.getSource() == otherButtons[10]){   //10 is ^2
            num1 =
           
        }
        
        if(e.getSource() == otherButtons[12]){   //12 is 1/x
            num1 =
            field.setText(""+(1/num1));
        }
        
        if(e.getSource() == otherButtons[9]){   //9 is √
            num1 =
           
        }
        
        if(e.getSource() == otherButtons[8]){   //8 is %
            num1 =
            field.setText("");
            num2 =
            field.setText(""+ num1*(num2 / 100));
        }
        
        /*if(e.getSource() == otherButtons[11]){   //11 is ←
            num1 =
            field.setText();
        }*/
        
        if(e.getSource() == otherButtons[1]){       //if = button pressed:
            num2 = //set num2 to new entered number
            
                //if = is pressed and if:
                if(operator == 2){
                    total = num1 + num2;
                }else if(operator == 3){
                    total = num1 - num2;
                }else if(operator == 4){
                    total = num1 * num2;
                }else if(operator == 5){
                    total = num1 / num2;
                }
            
            operator = 0; //if = is pressed but no operator inserted
            field.setText("" + total); //display result
        }
        
        
    }

    MAIN METHOD
    public static void main(String[] args) {
        JFrame frame = new JFrame("Calculator");
           
            frame.setResizable(false);
            frame.setLayout(new BorderLayout());
            frame.add(new Calculator(), BorderLayout.CENTER);
            frame.pack();
           
            frame.setVisible(true);
            frame.setSize(320, 400); //width, height
            
        
    }
    
}

SalmanFazal
Автор

Some constructive criticism: It would greatly help me as well as others if you could explain the concepts and reasoning for using them before just throwing them in there. Got my code to compile but it would've helped if you explained your code as you did it. Otherwise, great job!

breakerforu