0

I'm currently working on a calculator using GUI.

This is what I mean and how it should work.

  1. After entering a sequence of number operator number the user can click: a. ‘=’, in which case the calculator must display: i. the ‘=’ symbol after the last digit of the second number ii. the result of the operation, on a new line iii. anything else entered after the ‘=’ symbol is part of a new calculation and must be displayed on a separate line

For example, the user clicks: 123.45+456.2=1”. The screen should look like this:

  • 123.45+ entered by a user

  • 456.2= entered by a user

  • 579.65 calculated & displayed by your program

That is how I want the calculator to show the previous inputs and go to the new line once a mathematical operator has been clicked. Note, I've tried append as well but it didn't work.

Code:

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

public class CalculatorFrame extends JFrame {

 /**
  * All the buttons that will be used in the calculator have been initialized 
  */
 private JButton button1;
 private JButton button2; 
 private JButton button3;
 private JButton button4;
 private JButton button5;
 private JButton button6; 
 private JButton button7;
 private JButton button8;
 private JButton button9;
 private JButton button0; 

 private JButton buttonEqual;
 private JButton buttonDot;

 private JButton buttonClearLast;
 private JButton buttonClearAll;

 private JButton buttonAdd;
 private JButton buttonSub;
 private JButton buttonMul;
 private JButton buttonDiv;

 private JTextArea textArea; 
 private JScrollPane scrollPane;

 private JTextField textFieldResult;

 String display = "";
 private double TEMP;
 private double equalTemp;
 private int clearLastChar = 1;

 Boolean additionBoolean = false;
 Boolean subtractionBoolean = false;
 Boolean multiplicationBoolean = false;
 Boolean divisionBoolean = false;

 public CalculatorFrame(){

  JPanel panel2 = new JPanel();  
  panel2.setLayout(new GridLayout(1,1));
  panel2.add(buttonClearLast = new JButton ("Clear Last"));
  panel2.add(buttonClearAll = new JButton ("Clear All"));
  add(panel2, BorderLayout.PAGE_START);

  JPanel panel3 = new JPanel();
  textArea = new JTextArea();
  scrollPane = new JScrollPane(textArea);
  scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
  add(scrollPane);
  add(panel3, BorderLayout.AFTER_LAST_LINE);  

  JPanel panel1 = new JPanel();
  panel1.setLayout(new GridLayout(4,4));  

  panel1.add(button7 = new JButton ("7"));
  panel1.add(button8 = new JButton ("8"));
  panel1.add(button9 = new JButton ("9"));
  panel1.add(buttonAdd = new JButton ("+"));
  panel1.add(button4 = new JButton ("4"));
  panel1.add(button5 = new JButton ("5"));
  panel1.add(button6 = new JButton ("6"));
  panel1.add(buttonSub = new JButton ("-"));
  panel1.add(button1 = new JButton ("1"));
  panel1.add(button2 = new JButton ("2"));
  panel1.add(button3 = new JButton ("3"));
  panel1.add(buttonMul = new JButton ("*"));
  panel1.add(button0 = new JButton ("0"));
  panel1.add(buttonDot = new JButton ("."));
  panel1.add(buttonEqual = new JButton ("="));
  panel1.add(buttonDiv = new JButton ("/"));  
  add(panel1, BorderLayout.PAGE_END);

  pack();
  buttonClearLast.addActionListener(new ListenToClearLast());
  buttonClearAll.addActionListener(new ListenToClearAll());

  button1.addActionListener(new ListenToOne());
  button2.addActionListener(new ListenToTwo());
  button3.addActionListener(new ListenToThree());
  button4.addActionListener(new ListenToFour());
  button5.addActionListener(new ListenToFive());
  button6.addActionListener(new ListenToSix());
  button7.addActionListener(new ListenToSeven());
  button8.addActionListener(new ListenToEight());
  button9.addActionListener(new ListenToNine());  
  button0.addActionListener(new ListenToZero());

  buttonAdd.addActionListener(new ListenToAdd());
     buttonSub.addActionListener(new ListenToSub());
   buttonMul.addActionListener(new ListenToMul());
   buttonDiv.addActionListener(new ListenToDiv());

   buttonEqual.addActionListener(new ListenToEqual());
   buttonDot.addActionListener(new ListenToDot());

 }

 /**
  * This is where the action listener listens to all the button being pressed
  * Once heard, it will show case it to the TextArea of the calculator. 
  */

 public class ListenToOne implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("1");
  }
 }

 public class ListenToTwo implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("2");
  }
 }

 public class ListenToThree implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("3");
  }
 }

 public class ListenToFour implements ActionListener{
  public void actionPerformed(ActionEvent e){
 //  display = textArea.getText();
   textArea.append("4");
  }
 }

 public class ListenToFive implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("5");
  }
 }

 public class ListenToSix implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("6");
  }
 }

 public class ListenToSeven implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("7");
  }
 }

 public class ListenToEight implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("8");
  }
 }

 public class ListenToNine implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("9");
  }
 }

 public class ListenToZero implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("0");
  }
 }

 // This is used for decimal points. 
 // If the dot button is clicked, it will display "." 
 public class ListenToDot implements ActionListener{
  public void actionPerformed(ActionEvent e){
 //  display = textArea.getText();
   textArea.append(".");
  }
 }

 // The next 4 methods are for the basic operators. 
 // If any of the operator button is clicked, it would set it's boolean value to true and 
 // tell the program which operation to perform 

 public class ListenToAdd implements ActionListener{
  public void actionPerformed (ActionEvent e){
   TEMP = Double.parseDouble(textArea.getText());
   textArea.append("+\n");
   additionBoolean = true;
  }
 }

 public class ListenToSub implements ActionListener{
  public void actionPerformed (ActionEvent e){
   TEMP = Double.parseDouble(textArea.getText());
   textArea.setText("- \n");
   subtractionBoolean = true;
  }
 }

 public class ListenToMul implements ActionListener{
  public void actionPerformed (ActionEvent e){
   TEMP = Double.parseDouble(textArea.getText());
   textArea.setText("* \n");
   multiplicationBoolean = true;
  }
 }

 public class ListenToDiv implements ActionListener{
  public void actionPerformed (ActionEvent e){
   TEMP = Double.parseDouble(textArea.getText());
   textArea.setText("/ \n");
   divisionBoolean = true;
  }
 }

 // This ListenToEqual method does all the calculation
 // First, the program is checking what kind of calculation to perform by comparing it's boolean values. 
 // Once that is done, it will get the previous input from the user using the getText method and add/sub/mul/div with the new value 
 // The output will be displayed in the text area. 

 public class ListenToEqual implements ActionListener{
  public void actionPerformed (ActionEvent e){

   equalTemp = Double.parseDouble(textArea.getText());
   if (additionBoolean == true)
    equalTemp = equalTemp + TEMP;
   else if (subtractionBoolean == true)
    equalTemp = TEMP - equalTemp;
   else if (multiplicationBoolean == true)
    equalTemp = equalTemp * TEMP;
   else if (divisionBoolean == true)
    equalTemp = TEMP / equalTemp;

   textArea.append(Double.toString(equalTemp)); 
  // textArea.setText("1");

   additionBoolean = false;
   subtractionBoolean = false;
   multiplicationBoolean = false;
   divisionBoolean = false;
  }
 }

 public class ListenToClearAll implements ActionListener{
  public void actionPerformed (ActionEvent e){
   textArea.setText("");
   additionBoolean = false;
   subtractionBoolean = false;
   multiplicationBoolean = false;
   divisionBoolean = false;
   TEMP = 0;
   equalTemp = 0;
  }
 }

 public class ListenToClearLast implements ActionListener{
  public void actionPerformed (ActionEvent e){
   String currentChar = textArea.getText();
   String currentCharMinus = currentChar.substring(0,currentChar.length()-clearLastChar);
   textArea.setText(currentCharMinus);
  }
 }
}

This is how my calculator looks.

calculator:

https://i.stack.imgur.com/QEmIC.png

Any help on how I can display the output as it is in the example above.

Thank you.

Jainam Patel
  • 41
  • 2
  • 3
  • 12

4 Answers4

0

Your code will only return your answer because of assignment operator. Try using multiple variables to store your values then use "\n" to break them where you want them to break.

ArJay
  • 80
  • 1
  • 12
  • Hey, I've used \n to skip the line as u said. But how would I keep track of the previous inputs and display it to the textarea along with operator – Jainam Patel Nov 11 '18 at 19:16
  • int var1. When you click any of the operators then you assign the value on the text area to your variable before computing to get result. – ArJay Nov 11 '18 at 19:34
0

You want the numbers to go into same line as long as they are 0-9, right? This will do it. Instead of making 10 objects of JButton, create one array of it and initialize them using a loop, and add an actionlistener to them accordingly.

private JButton[] buttons;

buttons = new JButton[10];

for(int i = 0; i < buttons.length; i++) {
        // Make all the buttons and add them to the panel
        panel1.add(buttons[i] = new JButton(String.valueOf(i)));
        // Add an actionlistener to each of them
        buttons[i].addActionListener(this);
    }

And here is how you use the actionListener interface for these buttons (make sure to implement it in your CalculatorFrame class in the beginning):

@Override
public void actionPerformed(ActionEvent e) {
    for(int i = 0; i < buttons.length; i++) {
        // Check if the button pressed was a button0 - button 9
        if(e.getSource() == buttons[i]) {
            // whichever button (0-9) was pressed, append its result into display string
            display += String.valueOf(i);
        }
    }
    // Now set the result into your text area
    textArea.setText(display);
}

Now every time a button is pressed, it will be in the same line instead of a new one because you're not directly changing the value of textArea, but instead you are putting a string into it which is being appended every time you press a button.

So initially, the value of display variable is nothing. When you press 1, it becomes one and is displayed in the textArea. Now when you press 2, the value of display becomes display = display + "2". This time when you pass the display variable into textArea it doesn't just lose the value because it's not directly being edited.

You can use this logic to fix your other methods. Also since all the values are Strings, to perform calculations, you will need to convert String into an integer. You can use Integer.valueOf(display) is this case.

Hope this helps.

Naeem Khan
  • 950
  • 4
  • 13
  • 34
0
display = textArea.getText();
textArea.setText(display + "3");

Don't use getText() and setText(). It is not very efficient.

Every time you use getText() the text area needs to parse the Document to create a string. Every time you use setText() the text area needs to parse the String to create the Document.

Instead you just use:

textArea.append( "3" );

Even better yet, don't use custom listeners for each button. You can share a generic listener for the number buttons. See: How to add a shortcut key for a jbutton in java? for an example to get you started.

I want the calculator to show the previous inputs and go to the new line once a mathematical operator has been clicked.

Then, the additon ActionListener (for example) would do something like:

textArea.append( "+\n" );

You would need to do that for all your operators.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Okay so after adding what you've mentioned, I was able to meet most of the requirement. Now when I tried displaying the subtraction, multiplication and division sings at the end of the numbers, it would replace the whole input with a "chosen operator" and not perform any calculation. Check the code. – Jainam Patel Nov 11 '18 at 19:50
  • `it would replace the whole input with a "chosen operator"` - I have no idea what that means. There is no secret to using the append() method. It will append exactly what you tell it to append. So if you don't see the proper symbol, then you need to do some basic debugging. Did you use a debugger to step through the code to see the logic flow? Did you add System.out.println(...) statement to each ActionListner to see if it is being executed. These are basic debugging steps YOU need to do. – camickr Nov 11 '18 at 20:37
  • `it would replace the whole input with a "chosen operator"` - There is no secret to using the append() method. It will append exactly what you tell it to append. If you only see the operator you want to append, then that means somewhere in your code you are using setText() instead of the append() method. You need to do some basic debugging. Did you use a debugger to step through the code to see the logic flow? Did you add System.out.println(...) statement to each ActionListener to see if it is being executed. These are basic debugging steps YOU need to do. – camickr Nov 11 '18 at 22:12
  • Did you use append() for all the operators or only the "+" operator? Now that you have your answer don't forget to "accept" an answer so people know the problem has been solved. – camickr Nov 11 '18 at 22:14
0

To Display the text after the operations as you have indicated above you can do it by adding to the setText method a nesessary text: textArea.setText(display + "+ entered by user\n") or anything like this. But it will not help you to get a result and you'll get an error message. Why? Because you have a problem with reading of the second variable "equalTemp = Double.parseDouble(textArea.getText())". In fact this method takes out ALL values/chars/etc displayed in the textArea and thus will give you an error message, because it is not possible to transform them all into Double format. To solve this problem you have to change the way of saving of the entered values. For example you can convert all text in the textArea into a String and then split() it with specific symbol and after that save the remained values as Double ones.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.regex.PatternSyntaxException;

class CalculatorFrame extends JFrame {

/**
 * All the buttons that will be used in the calculator have been initialized 
 */
private JButton button1;
private JButton button2; 
private JButton button3;
private JButton button4;
private JButton button5;
private JButton button6; 
private JButton button7;
private JButton button8;
private JButton button9;
private JButton button0; 

private JButton buttonEqual;
private JButton buttonDot;

private JButton buttonClearLast;
private JButton buttonClearAll;

private JButton buttonAdd;
private JButton buttonSub;
private JButton buttonMul;
private JButton buttonDiv;

private JTextArea textArea; 
private JScrollPane scrollPane;

String display = "";
String[] arr;
private double result;

Boolean additionBoolean = false;
Boolean subtractionBoolean = false;
Boolean multiplicationBoolean = false;
Boolean divisionBoolean = false;
Boolean equals = false;

public CalculatorFrame(){

    JPanel panel2 = new JPanel();       
    panel2.setLayout(new GridLayout(1,1));
    panel2.add(buttonClearLast = new JButton ("Clear Last"));
    panel2.add(buttonClearAll = new JButton ("Clear All"));
    add(panel2, BorderLayout.PAGE_START);

    JPanel panel3 = new JPanel();
    textArea = new JTextArea(10, 20);
    scrollPane = new JScrollPane(textArea);

scrollPane.setVerticalScrollBarPolicy(
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    add(scrollPane);
    add(panel3, BorderLayout.AFTER_LAST_LINE);      

    JPanel panel1 = new JPanel();
    panel1.setLayout(new GridLayout(4,4));      


    panel1.add(button7 = new JButton ("7"));
    panel1.add(button8 = new JButton ("8"));
    panel1.add(button9 = new JButton ("9"));
    panel1.add(buttonAdd = new JButton ("+"));
    panel1.add(button4 = new JButton ("4"));
    panel1.add(button5 = new JButton ("5"));
    panel1.add(button6 = new JButton ("6"));
    panel1.add(buttonSub = new JButton ("-"));
    panel1.add(button1 = new JButton ("1"));
    panel1.add(button2 = new JButton ("2"));
    panel1.add(button3 = new JButton ("3"));
    panel1.add(buttonMul = new JButton ("*"));
    panel1.add(button0 = new JButton ("0"));
    panel1.add(buttonDot = new JButton ("."));
    panel1.add(buttonEqual = new JButton ("="));
    panel1.add(buttonDiv = new JButton ("/"));  
    add(panel1, BorderLayout.PAGE_END);


    pack();
//  buttonClearLast.addActionListener(new ListenToClearLast());
    buttonClearAll.addActionListener(new ListenToClearAll());

    button1.addActionListener(e -> {textArea.setText(display() + "1");});
    button2.addActionListener(e -> {textArea.setText(display() + "2");});
    button3.addActionListener(e -> {textArea.setText(display() + "3");});
    button4.addActionListener(e -> {textArea.setText(display() + "4");});
    button5.addActionListener(e -> {textArea.setText(display() + "5");});
    button6.addActionListener(e -> {textArea.setText(display() + "6");});
    button7.addActionListener(e -> {textArea.setText(display() + "7");});
    button8.addActionListener(e -> {textArea.setText(display() + "8");});
    button9.addActionListener(e -> {textArea.setText(display() + "9");});      
    button0.addActionListener(e -> {textArea.setText(display() + "0");});

    buttonAdd.addActionListener(e -> {textArea.setText(display() + "+ enterd by user\n"); additionBoolean = true;});
    buttonSub.addActionListener(e -> {textArea.setText(display() + "- enterd by user\n"); subtractionBoolean = true;});
    buttonMul.addActionListener(e -> {textArea.setText(display() + "* enterd by user\n"); multiplicationBoolean = true;});
    buttonDiv.addActionListener(e -> {textArea.setText(display() + "/ enterd by user\n"); divisionBoolean = true;});
    buttonDot.addActionListener(e -> {textArea.setText(display() + ".");});

    buttonEqual.addActionListener(e -> {calculation();
                                        textArea.setText(display() + "= enterd by user\n" + result + " this is your result");
                                        });
   }

private String display() {
    display = textArea.getText();
    return display;
    }

private void calculation() {
    String str = display();

    if (additionBoolean == true) {
        arr = str.split("\\+ enterd by user");
        result = Double.parseDouble(arr[0]) + Double.parseDouble(arr[1]);
        }
    else if (subtractionBoolean == true) {
        arr = str.split("- enterd by user");
        result = Double.parseDouble(arr[0]) - Double.parseDouble(arr[1]);
        }
    else if (multiplicationBoolean == true) {
        arr = str.split("\\* enterd by user");
        result = Double.parseDouble(arr[0]) * Double.parseDouble(arr[1]);
        }
    else if (divisionBoolean == true) {
        arr = str.split("/ enterd by user");
        result = Double.parseDouble(arr[0]) / Double.parseDouble(arr[1]);
        }
}
/**
 * This is where the action listener listens to all the button being pressed
 * Once heard, it will show case it to the TextArea of the calculator. 
 */

public class ListenToClearAll implements ActionListener{
    public void actionPerformed (ActionEvent e){
        textArea.setText("");
        additionBoolean = false;
        subtractionBoolean = false;
        multiplicationBoolean = false;
        divisionBoolean = false;
    }
}
} 

You'll get next result for a sum of 9.25 and 23.7, as an example:

9.25+ enterd by user
23.7= enterd by user
32.95 this is your result
Sergei Voychuk
  • 171
  • 2
  • 8