HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Calculator in Java using JFrame

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
jframecalculatorusingjava

Problem

Today, I made a calculator in JFrame. The code is a little long but I'm still a beginner to Java. In the future I'm going to do some improvements on it, but here it is right now.

This is the meat of the calculator:

```
@SuppressWarnings("unused")
public class CalcSubClass extends JFrame {
private static final long serialVersionUID = 1L;

JTextField numDisplay;
JButton zero;
JButton one;
JButton two;
JButton three;
JButton four;
JButton five;
JButton six;
JButton seven;
JButton eight;
JButton nine;
JButton add;
JButton subtract;
JButton multiply;
JButton divide;
JButton percent;
JButton equals;
JButton clear;
String addString;
String subString;
String multiString;
String divString;
String finalString;
double addDouble;
double subDouble;
double multiDouble;
double divDouble;
double finalDouble;
double answer;
String answerAsString;
String percentAsString;
double percentAsDouble;
double prcntAnswerAsDouble;
String prcntAnswerAsString;
JButton decimalPoint;

public static double add(double num1, double num2) {

return num1 + num2;
}

public static double subtract(double num1, double num2) {

return num1 - num2;
}

public static double multiply(double num1, double num2) {

return num1 * num2;
}

public static double divide(double num1, double num2) {

return num1 / num2;
}

public CalcSubClass() {
super("Calculator");
setLayout(new GridBagLayout());

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);

GridBagConstraints gbc = new GridBagConstraints();

numDisplay = new JTextField();
numDisplay.setPreferredSize(new Dimension(130, 30));
numDisplay.setEditable(false);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 3;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(numDisplay, gbc);

zero = new JButton("0");
gbc.gridx = 1;
gbc.gridy = 5;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(zero, gbc);

one = new JButton("1");

Solution

Calculators seem really popular...

I'll start with what stands out.
new JButton("÷"); This likely doesn't work for you and definitely won't work everywhere, to use the Obelus you want to refer to its unicode, so rather instantiate using new JButton("\u00F7");

Instead of having all those variables for your number buttons simple create an array.

JButton[] buttons = new JButton[10];

and instantiate using a loop, which you can also leverage to add the relevant action listeners using a lambda expression

As an example of a Lambda Expression, you have a lot of places where you write this code:

addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            // content
        }
    });


this can be shortened to just

addActionListener(e -> {
 // content
});


As we see in the loop:

for (int i = 0; i  numDisplay.setText(numDisplay.getText() + val));
}


If you're worried about positioning consider using a layout manager and placing the buttons within, e.g.
JPanel numberPanel = new JPanel(new GridLayout(0, 3));
of course with that in our loop we would also call numberPanel.add(buttons[i]);

Your many static methods are very similar, you can simplify them by using an interface method also using lambda expressions.

First, defining the interface:

We know we always have two inputs with doubles as input and return value, so:

interface Equation {
    double compute(double alpha, double beta);
}


and now an enumeration to use it:

public enum Operation implements Equation {
    ADD("+", (x, y) -> x + y),
    SUBTRACT("-", (x, y) -> x - y),
    MULTIPLY("x",(x, y) -> x * y),
    DIVIDE("\u00F7", (x, y) -> x / y);

    private final Equation equation;
    private final String symbol

    Operation(String symbol, Equation equation) {
        this.symbol = symbol;
        this.equation = equation;
    }

    @Override
    public double compute(double alpha, double beta) {
        return equation.compute(alpha, beta);
    }

    @Override
    public String toString() {
        return symbol;
    }
}


You can make operator buttons like so:

JButton[] operatorButtons = new JButton[Operation.values().length];
for (int i = 0; i  numDisplay.setText(op.compute(/* */));
}

Code Snippets

addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            // content
        }
    });
addActionListener(e -> {
 // content
});
for (int i = 0; i < buttons.length; i++) {
  String val = Integer.toString(i)
  buttons[i] = new JButton(val);
  buttons[i].addActionListener(e -> numDisplay.setText(numDisplay.getText() + val));
}
interface Equation {
    double compute(double alpha, double beta);
}
public enum Operation implements Equation {
    ADD("+", (x, y) -> x + y),
    SUBTRACT("-", (x, y) -> x - y),
    MULTIPLY("x",(x, y) -> x * y),
    DIVIDE("\u00F7", (x, y) -> x / y);

    private final Equation equation;
    private final String symbol

    Operation(String symbol, Equation equation) {
        this.symbol = symbol;
        this.equation = equation;
    }

    @Override
    public double compute(double alpha, double beta) {
        return equation.compute(alpha, beta);
    }

    @Override
    public String toString() {
        return symbol;
    }
}

Context

StackExchange Code Review Q#97430, answer score: 7

Revisions (0)

No revisions yet.