Creating simple Calculator in Java

Introduction

This tutorial is about creating simple calculator which performs only four operations. For creating a simple Calculator we require two JTextFields where the user can enter two numbers, four JButton for four operations namely addition, subtraction,multiplication and division, a JLabel for displaying the result.

Implementation

Step 1: Creating a class which extends JFrame because we are going to create an Application. After this we have to define the constructor of the class as follows. Super() is used to give title to the frame. SetBackground() method is used to change the background color of the frame.
  1. super("Simple Calculator");
  2. setBackground(Color.GRAY);
Step 2: Creating text fields, labels and adding those to frame.
  1. xInput = new JTextField("0", 10);
  2. yInput = new JTextField("0", 10);
xInput and yInput are the text fields where user can enter two numbers. Initial value in the text field is 0 and size is 10. Next we create separate labels for displaying “x=” and “y=” and add these labels to separate panels as follows.
  1. JPanel xPanel = new JPanel();
  2. xPanel.add( new JLabel(" x = "));
  3. xPanel.add(xInput);
Similarly we have to create yPanel and add labels and text fields to it. Step 3: Creating buttons for different Operators We will create a button panel in which we will add four buttons for four operators: +, -, *,/. These four buttons are added to the panel using Grid Layout with one row and four columns so that all the buttons are of same size. Once a user clicks on these button suitable action is performed, for those events we require adding ActionListener to those buttons.
  1. JPanel buttonPanel = new Jpanel(); //panel for the four buttons
  2. buttonPanel.setLayout(new GridLayout(1,4)); // panel has 1 row and four columns.
  3. JButton plus = new Jbutton("+"); // Button with “+” text on it
  4. plus.addActionListener(this); // ActionListener is present in the same class.
  5. buttonPanel.add(plus);
Similarly other buttons can be created and added to the buttonPanel. Step 4: Adding all the panels to the frame Next we create label for displaying the result and add the label and previously created panels to the frame.
  1. answer = new JLabel("x + y = 0", Jlabel.CENTER); // text on label will align in the center of the label.
  2. answer.setForeground(Color.red); //sets foreground color
  3. answer.setBackground(Color.white); //sets background color
  4. answer.setOpaque(true); // make sure background color is visible
Finally set up the layout for the frame, using a GridLayout having 4 rows, 1 column , 3 pixel vertical gaps between rows , also 3 pixel horizontal gap between the columns. Then add all the components that have been created.
  1. setLayout(new GridLayout(4,1,3,3));
  2. add(xPanel);
  3. add(yPanel);
  4. add(buttonPanel);
  5. add(answer);
Step 5: Defining actionPerformed() method for Listening to the events This method is called when a user clicks on any of the four buttons. When the user clicks on the button, text from two text fields is stored into variables and depending on which button is clicked, the result is calculated and displayed on the answer label.
  1. double x, y; // The numbers from the input boxes.
  2.  
  3. /*The try...catch
  4.   statement will check for errors in the String. If
  5.   the string is not a legal number, the error message
  6.   "Illegal data for x." is put into the answer and
  7.   the actionPerformed() method ends. */
  8.  
  9. try {
  10. String xStr = xInput.getText(); // get the content of the field as String
  11. x = Double.parseDouble(xStr); // convert String data type to double
  12. }
  13. catch (NumberFormatException e) {
  14. // The string xStr is not a legal number.
  15. answer.setText("Illegal data for x.");
  16. xInput.requestFocus();
  17. return;
  18. }
Similarly text from other field is obtained and stored into y variable. Next, perform the operation based on the action command from the button. Note that division by zero produces an error message.
  1.  
  2. String op = evt.getActionCommand(); //let you know which button was clicked.
  3. if (op.equals("+")) //calculates the result and display on answer label.
  4. answer.setText( "x + y = " + (x+y) );
  5. else if (op.equals("-"))
  6. answer.setText( "x - y = " + (x-y) );
  7. else if (op.equals("*"))
  8. answer.setText( "x * y = " + (x*y) );
  9. else if (op.equals("/")) {
  10. if (y == 0) //displays the results only if divider is not zero
  11. answer.setText("Can't divide by zero!");
  12. else
  13. answer.setText( "x / y = " + (x/y) );
  14. }
Step 6: Write the main() method and initialize the object setResizable(false) is used to disable changing size of the frame window.
  1. public static void main(String[] args) {
  2. SimpleCalc calc = new SimpleCalc(); //creates the object
  3. calc.setLocation(100,100);
  4. calc.setSize(300,200);
  5. calc.setResizable(false);
  6. calc.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); //close the application when close button of the frame is clicked.
  7. calc.setVisible(true);
  8. }

Comments

Submitted bymoti (not verified)on Fri, 12/12/2014 - 20:35

it is best programing

Add new comment