user3645728 user3645728 - 7 months ago 10
Java Question

I'm having some errors with GUI

I'm having some errors in making a calculator program , I've tried many things but nothing works , my errors are.


  1. When you click any number button it continues with the default value zero ("0 is my default text for the calculator")

  2. When you insert a number in the calculator and if the text field has an old answer , the number you pressed will add to the answer that you had gotten.



Please help!

import javax.swing.*;
import java.math.*;
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);
numberButtons[i].addActionListener(this); // 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];

otherButtons[i].addActionListener(this);

add(otherButtons[i], gbc);

}

// Display text field
field = new JTextField(); // define field
field.setBorder(BorderFactory.createLineBorder(Color.BLACK)); // set border color to black
field.setEditable(false); // cannot be edited
field.setFont(new Font("Arial", Font.PLAIN, 26)); // font style and size
field.setHorizontalAlignment(field.RIGHT);
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] && !field.getText().contains(".")) { // 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 vslue to positive or negative)
field.setText("" + (-1 * Integer.parseInt(field.getText()))); // 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 = Integer.parseInt(field.getText());
operator = 2;
field.setText("");
}

if (e.getSource() == otherButtons[3]) { // 3 is -
num1 = Integer.parseInt(field.getText());
operator = 3;
field.setText("");
}

if (e.getSource() == otherButtons[4]) { // 4 is *
num1 = Integer.parseInt(field.getText());
operator = 4;
field.setText("");
}

if (e.getSource() == otherButtons[5]) { // 5 is /
num1 = Integer.parseInt(field.getText());
operator = 5;
field.setText("");
}

if (e.getSource() == otherButtons[10]) { // 10 is ^2
num1 = Integer.parseInt(field.getText());
field.setText("" + (num1 * num1));
}

if (e.getSource() == otherButtons[12]) { // 12 is 1/x
num1 = Integer.parseInt(field.getText());
field.setText("" + (1 / num1));
}

if (e.getSource() == otherButtons[9]) { // 9 is ?
num1 = Integer.parseInt(field.getText());
field.setText("" + (Math.sqrt(num1)));
}

if (e.getSource() == otherButtons[8]) { // 8 is %
num1 = Integer.parseInt(field.getText());
field.setText("");
num2 = Integer.parseInt(field.getText());
field.setText("" + num1 * (num2 / 100));
}

if (e.getSource() == otherButtons[1]) { // if = button pressed:
num2 = Integer.parseInt(field.getText()); // 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;
}

else {
field.setText("");
}

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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLayout(new BorderLayout());
frame.add(new Calculator(), BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// frame.setSize(320, 400); //width, height

}

}

Answer

total should be a local variable initialized to 0, before the if statements calculating the total.

For clearing the total

private boolean clearOnKeyPress = false;

    double total = 0;
    if ...
    clearOnKeyPress = true;
    operator = 0;
    field.setText("" + total); //display result

For not appending to 0:

    if (e.getSource() == numberButtons[i]) {
        if (clearOnKeyPress || field.getText().equals("0")) {
            field.setText(""):
            clearOnKeyPress = false;
        }
        field.setText(field.getText() + i);
    }

Another way, without boolean flag, would be to use field.selectAll()' selecting the entire total, andfield.cut()` on a number press, removing any selection.