Sunday, November 27, 2016

Create Simple Calculator using JAVA GUI

Filled under:

Here I give you a simple program to create Calculator using Java GUI. Please use this website as a reference link if you want to copy and paste this program.
If any question, don't be hesitate to leave a comment or contact my email.



package week09;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;

/**@author Novida Wayan Sari (1606954930)
 * @version 20161127 07:35PM
 * This class is Calculator class which is used to count a simple mathematics operation
 * such as plus, minus, multiply and divide.
 * This application is created to complete weekly task of Dasar-Dasar Pemrograman lecturing subject.
 * This application uses JPanel as for the main component of GUI
 * */

public class Calculator extends JPanel implements ActionListener {
    private static final int WIDTH = 420; //constant of frame width
    private static final int HEIGHT = 252; //constant of frame height
    private JMenuBar menuBar; //Menu Bar (File, Help) <-- I do not have any idea to fill up the content
    private JMenu fileMenu, helpMenu; //Referring Menu Bar, the content of menu bar
   
    //mainPanel is a JPanel contains of main components except Menu Bar
    //bottomPanel is a JPanel container of angkaPanel and operatorPanel
    //angkaPanel is a JPanel container of all number button and "+" and "-" [Grid Layout]
    //operatolPanel is a JPanel container of all operators button except "+" and "-" [Grid Layout]
    private JPanel mainPanel, bottomPanel, angkaPanel, operatorPanel;
    //-------------------------------------------------------------------------------------------------
    private JButton[] btnAngka; //Array of number button {"0","1","2","3","4","5","6","7","8","9"}
    private JButton[] btnControl; //Arrays of control button {"Backspace","C"}
    private JButton[] btnOperator; //Array of operator button {"+","-","/","*","="}
    private JTextField input; //Text field of input
    private Color bckColor, mainColor, inputColor, textColor; //Colors used to make background, foreground color in this application
    private float numb1 = 0; //variable which is used to save temporary value inputed by user
    private String oldOperator = ""; //variable which is used to save temporary operator inputed by user
    private boolean status = false; //the status to show if the operation is end
   
    /*constructor
     * */
    public Calculator(){
        this.bckColor = new Color(205,92,92); //Background Color
        this.mainColor = new Color(128,0,0); //Button Color
        this.inputColor = new Color(255,182,193); //Textfield background color
        this.textColor = new Color(255,182,193); //Text of text field color
       
        /*Main Panel uses Flow Layout which contains of Menu Bar and Main Panel*/
        super.setLayout(new FlowLayout());
        super.setPreferredSize(new Dimension(this.WIDTH, this.HEIGHT));
        super.setBackground(bckColor);
        super.setForeground(Color.WHITE);
       
        /*----------------- Menu Bar ------------------------------------------------*/
        this.menuBar = new JMenuBar();
        this.menuBar.setPreferredSize(new Dimension(this.WIDTH-20, 30));
        this.menuBar.setLocation(10, 0);
        this.menuBar.setBackground(bckColor);
        this.menuBar.setForeground(Color.white);
        this.fileMenu = new JMenu("File");
        this.helpMenu = new JMenu("Help");
        this.menuBar.add(fileMenu);
        this.menuBar.add(helpMenu);
        /*----------------- End of Menu Bar -----------------------------------------*/
       
        /*----------------- Input -----------------------------------------------------------------------------*/
        this.input = new JTextField();
        this.input.setPreferredSize(new Dimension(this.WIDTH-20, 30));
        this.input.setBackground(inputColor);
        this.input.setForeground(bckColor);
        this.input.setHorizontalAlignment(JLabel.RIGHT);
        this.input.setBorder(new LineBorder(bckColor));
        this.input.setBorder(BorderFactory.createCompoundBorder(this.input.getBorder(), BorderFactory.createEmptyBorder(5, 5, 5, 5)));
        this.input.setFont(new Font(this.input.getFont().getName(),Font.BOLD,this.input.getFont().getSize()));
        this.input.setEditable(false);
        this.input.setText("0");
        /*---------------- End of Input-------------------------------------------------------------------------*/
       
        /*---------------- Number Button -----------------------------------------------------------*/
        this.btnAngka = new JButton[10];
        this.btnControl = new JButton[2];
        this.btnOperator = new JButton[6];
       
        int colNum = 4;
        for(int i=0;i<10;i++){
            this.btnAngka[i] = new JButton(""+i);
            this.btnAngka[i].setPreferredSize(new Dimension((this.WIDTH-20)/colNum,30));
            this.btnAngka[i].setBackground(mainColor);
            this.btnAngka[i].setForeground(textColor);
            this.btnAngka[i].setBorder(new LineBorder(bckColor));
            this.btnAngka[i].addActionListener(this);
        }
        /*--------------- End of Number Button ----------------------------------------------------*/
       
        /*--------------- Control Button ----------------------------------------------------------*/
        this.btnControl[0] = new JButton("Backspace");
        this.btnControl[1] = new JButton("C");
       
        for(int i=0;i<2;i++){
            this.btnControl[i].setPreferredSize(new Dimension((this.WIDTH-20)/colNum,30));
            this.btnControl[i].setBackground(mainColor);
            this.btnControl[i].setForeground(textColor);
            this.btnControl[i].setBorder(new LineBorder(bckColor));
            this.btnControl[i].addActionListener(this);
        }
        /*--------------- End of Control Button ---------------------------------------------------*/
       
        /*--------------- Operator Button ---------------------------------------------------------*/
        this.btnOperator[0] = new JButton("+");
        this.btnOperator[1] = new JButton("-");
        this.btnOperator[2] = new JButton("/");
        this.btnOperator[3] = new JButton("*");
        this.btnOperator[4] = new JButton(".");
        this.btnOperator[5] = new JButton("=");
       
        for(int i=0;i<6;i++){
            this.btnOperator[i].setPreferredSize(new Dimension((this.WIDTH-20)/colNum,30));
            this.btnOperator[i].setBackground(mainColor);
            this.btnOperator[i].setForeground(textColor);
            this.btnOperator[i].setBorder(new LineBorder(bckColor));
            this.btnOperator[i].addActionListener(this);
        }
        /*-------------- End of Operator Button --------------------------------------------------*/
       
        //------------ BACKSPACE BUTTON -----------------------------------------------------------
        this.btnControl[0].setPreferredSize(new Dimension((2*(this.WIDTH-20))/colNum,30));
        this.btnControl[0].setLocation(10,70);
        this.btnControl[0].setBackground(mainColor);
        this.btnControl[0].setForeground(textColor);
        this.btnControl[0].setBorder(new LineBorder(bckColor));
        //------------ END OF BACKSPACE -----------------------------------------------------------
       
        //------------ C BUTTON -----------------------------------------------------------
        this.btnControl[1].setPreferredSize(new Dimension((this.WIDTH-20)/colNum,30));
        this.btnControl[1].setBackground(mainColor);
        this.btnControl[1].setForeground(textColor);
        this.btnControl[1].setBorder(new LineBorder(bckColor));
        //------------ END OF C BUTTON -----------------------------------------------------------
       
        /*------------ Bottom Panel -------------------------------------------------------------*/
        this.bottomPanel = new JPanel();
        this.bottomPanel.setPreferredSize(new Dimension(this.WIDTH-20,120));
        this.bottomPanel.setLayout(new BorderLayout());
        /*------------ of Bottom Panel ----------------------------------------------------------*/
       
        /*------------ Panel of number button -----------------------------------------------------*/
        this.angkaPanel = new JPanel();
        this.angkaPanel.setPreferredSize(new Dimension((3*(this.WIDTH-20))/4,120));
        this.angkaPanel.setLayout(new GridLayout(4,3));
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                this.angkaPanel.add(this.btnAngka[(2-i)*3+1+j]);
            }
        }
   
        this.angkaPanel.add(this.btnOperator[0]);
        this.angkaPanel.add(this.btnAngka[0]);
        this.angkaPanel.add(this.btnOperator[1]);
        /*------------ End of Panel of number button ---------------------------------------------------*/
       
        this.bottomPanel.add(this.angkaPanel, BorderLayout.WEST);
       
        this.operatorPanel = new JPanel();
        this.operatorPanel.setPreferredSize(new Dimension((this.WIDTH-20)/4,120));
        this.operatorPanel.setLayout(new GridLayout(4,1));
       
        for(int i=0;i<4;i++){
            this.operatorPanel.add(this.btnOperator[i+2]);
        }
       
        this.bottomPanel.add(this.operatorPanel, BorderLayout.EAST);
       
        /*------------ insert all components to main Panel and add it to this class ---------------------*/
        this.mainPanel = new JPanel();
        this.mainPanel.setLayout(new BorderLayout());
        this.mainPanel.setBackground(bckColor);
            /*---------------------- Main Panel uses Border Layout ------------*/
        this.mainPanel.add(this.input, BorderLayout.NORTH);
        this.mainPanel.add(this.btnControl[0], BorderLayout.WEST);
        this.mainPanel.add(this.btnControl[1], BorderLayout.EAST);
        this.mainPanel.add(this.bottomPanel, BorderLayout.SOUTH);
            /*-----------------------------------------------------------------*/
        super.add(menuBar);
        super.add(mainPanel);
        /*-----------------------------------------------------------------------------------------------*/
    }
   
   
    @Override
    public void actionPerformed(ActionEvent evt) {
        // TODO Auto-generated method stub
        if(evt.getSource() instanceof JButton){
            String btnText = ((JButton)evt.getSource()).getText();
            String pattern = "[0-9]|[.]";
            if(btnText == "Backspace"){
                /*If the button pressed is backspace, then it will erase the last digit of shown inputed number*/
                if(!this.input.getText().equals("")){
                    /*if there is digit in the last, then system should check if it is not zero (integer or decimal)*/
                    if(this.input.getText().equals("0.")){
                        this.input.setText("0");
                    }else{
                        /*if there is digit in the last, then system should check if previous digit is exist*/
                        if(this.input.getText().substring(0, this.input.getText().length()-1).equals("")){
                            this.input.setText("0");
                        }else{
                            this.input.setText(this.input.getText().substring(0, this.input.getText().length()-1));
                        }
                    }
                }
                this.status = false; //it shows that there is no temporary operation, backspace doesn't make any calculation process
            }else if(btnText == "C"){
                /*C will clear all shown number and change it into zero ------------------
                 * it also will clean up the history of number and operator inputed by the user
                 * */
                this.input.setText("0");
                this.numb1 = 0;
                this.oldOperator = "";
                this.status = false;
            }else if(btnText.matches(pattern)){
                if(btnText.equals(".") && this.input.getText().equals("0")){
                    /*If only zero shown in screen, and the user presses point to input decimal number -------------*/
                    this.input.setText("0.");
                }else{
                    if(this.status == false){
                        if(this.input.getText().equals("0")){
                            /*If only zero show in screen, and the user presses any number, the zero in the first character shouldn't be shown*/
                            this.input.setText(btnText);
                        }else{
                            /*If the first number isn't zero, then the system only append pressed number*/
                            this.input.setText(this.input.getText()+btnText);
                        }
                    }else{
                        this.input.setText(btnText);
                    }
                }
               
                this.status = false;
            }else{
                try{
                    /*Every single time the user presses operator button, then the system should do calculation based on
                     *history of number and operator user pressed
                     **/
                    float result = this.count();
                    if(result == Math.floor(result)){
                        /*If the result of calculation can be figured out into integer form, then the system prioritize it first */
                        this.input.setText(""+(int)result);
                    }else{
                        this.input.setText(""+result);
                    }
                    this.status = true;
                }catch(NumberFormatException e){
                    JOptionPane.showMessageDialog(null, "There was an error occured. Please restart the application and then try again!");
                }
               
                if(btnText.equals("=")){
                    /*= button will shows the result and erase the history of number and operator inputed by the user such C button does */
                    this.oldOperator = "";
                    this.numb1 = 0;
                }else{
                    /*The system saves the operator as temporary operator to be executed in next operator pressed*/
                    this.oldOperator = btnText;
                }
            }
        }
    }
   
    public float count(){
        switch(this.oldOperator){
            case "+":this.numb1=this.numb1+Float.valueOf((this.input.getText()));break;
            case "-":this.numb1=this.numb1-Float.valueOf((this.input.getText()));break;
            case "/":this.numb1=this.numb1/Float.valueOf((this.input.getText()));break;
            case "*":this.numb1=this.numb1*Float.valueOf((this.input.getText()));break;
            case "":this.numb1=Float.valueOf((this.input.getText()));break;
        }
        return this.numb1;
    }
   
    public static void main(String[] arg){
        JFrame frame = new JFrame("Calculator");
        frame.setSize(Calculator.WIDTH, Calculator.HEIGHT);
        frame.setLocation(150, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
        Calculator calc = new Calculator();
        frame.add(calc);
        frame.setVisible(true);
    }

}

0 comments:

Post a Comment