Java GUI Calculator Tutorial (NEW) Part 4: Operations

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

Im 5 years late but you are awesome thanks a lot for this tutorial

echoraido
Автор

I have been following with this tutorial. I must have made a mistake somewhere. Whenever I click '=' on my calculator GUI, the answer is always 0.0. Please could somebody help me. I made my ints into doubles. By the way, I know it is lined up correctly. I can't be bothered to re line 194 lines of code.

package calculator;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Calculator extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;

public static final int WIDTH = 320;
public static final int HEIGHT = 480;

private GridBagLayout layout;
private GridBagConstraints gbc;

private JButton[] numberButtons;
private JButton[] opButtons;

private JTextField field;

private double num1, num2, ans;
private double op;

// [0] = gridx, [1] = gridy, [2] = gridwidth, [3] = gridheight
private int[][] numConstraints = new int[][] {
{0, 5, 2, 1},
{0, 4, 1, 1},
{1, 4, 1, 1},
{2, 4, 1, 1},
{0, 3, 1, 1},
{1, 3, 1, 1},
{2, 3, 1, 1},
{0, 2, 1, 1},
{1, 2, 1, 1},
{2, 2, 1, 1},
};

private int[][] opConstraints = new int[][] {
{2, 5, 1, 1},
{3, 4, 1, 2},
{3, 3, 1, 1},
{3, 2, 1, 1},
{3, 1, 1, 1},
{2, 1, 1, 1},
{1, 1, 1, 1},
{0, 1, 1, 1},
};

public Calculator() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));

layout = new GridBagLayout();
layout.columnWidths = new int[] {80, 80, 80, 80};
layout.rowHeights = new int[] {80, 80, 80, 80, 80, 80};
setLayout(layout);

gbc = new GridBagConstraints();

numberButtons = new JButton[10];
for (int i = 0; i < numberButtons.length; i++) {
numberButtons[i] = new JButton("" + i);


gbc.gridx = numConstraints[i][0];
gbc.gridy = numConstraints[i][1];
gbc.gridwidth = numConstraints[i][2];
gbc.gridheight = numConstraints[i][3];
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(2, 2, 2, 2);

add(numberButtons[i], gbc);
}

opButtons = new JButton[8];

opButtons[0] = new JButton(".");
opButtons[1] = new JButton("=");
opButtons[2] = new JButton("+");
opButtons[3] = new JButton("-");
opButtons[4] = new JButton("*");
opButtons[5] = new JButton("/");
opButtons[6] = new JButton("+/-");
opButtons[7] = new JButton("C");

for(int i = 0; i < opButtons.length; i++) {
gbc.gridx = opConstraints[i][0];
gbc.gridy = opConstraints[i][1];
gbc.gridwidth = opConstraints[i][2];
gbc.gridheight = opConstraints[i][3];



add(opButtons[i], gbc);
}

field = new JTextField();

field.setEditable(false);
field.setFont(new Font("Arial", Font.PLAIN, 24));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 4;
gbc.gridheight = 1;

add(field, gbc);
}

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);
}

public void actionPerformed(ActionEvent e) {
for(int i = 0; i < numberButtons.length; i++) {
if(e.getSource() == numberButtons[i]) {
+ i);
}
}

if(e.getSource() == opButtons[0] && {
+ ".");
}

if(e.getSource() == opButtons[6]) {
field.setText("" + (-1 *
}

if(e.getSource() == opButtons[7]) {
field.setText("");
}

if(e.getSource() == opButtons[2]) {
num1 =
op = 1;
field.setText("");
}

if(e.getSource() == opButtons[3]) {
num1 =
op = 2;
field.setText("");
}

if(e.getSource() == opButtons[4]) {
num1 =
op = 3;
field.setText("");
}

if(e.getSource() == opButtons[5]) {
num1 =
op = 4;
field.setText("");
}

if(e.getSource() == opButtons[1]) {
num2 =

if(op == 1) {

} else if(op == 2) {
ans = num1 + num2;
} else if(op == 3) {
ans = num1 - num2;
} else if(op == 3) {
ans = num1 * num2;
} else if(op == 4) {
ans = num1 / num2;
}

op = 0;
field.setText("" + ans);
}
}

}

hamandfraz
Автор

why didn't you fix the error and on mine when i try to press = it says Source)
at Source)
at Source)
at Source)

thethunderboss
Автор

Honestly this is kind of buggy, but it's good to learn basic Java I guess. Whenever the decimal and then +/- is pressed you get an error. If you don't clear after getting the answer and you try and do another sum it just adds the number to the end of the answer and produces errors when you try to press another operation button. Any ideas how to fix this?

MemekingSupreme
Автор

This is a good tutorial but the calculator does not work well. the decimal is completely broken you cannot add, subtract, multiply, divide with it

RMIXMODZ
Автор

Anyone who is having troubles with the decimals, replace the Integer.parseInt() methods with Double.parseDouble(). That should fix all problems.

PatrickFeltes
Автор

Thanks alot for the java bug of addiction ! :)

stringlights
Автор

I made a nice calculator using HTML, CSS3, and javascript. The button with the divide symbol is an A with a sqiggly line (~) over it and a dot to the right of it. What the hell is that?

orionlamothe
Автор

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
Автор

help please my calculator is so dumbbb
when i type 11+9 it gives me 20 LOL
its 21

meir
Автор

why ARE THERE ERRORS IN CONSOLE BUT THERES NO PROBLEMS

RealLava
join shbcf.ru