BASIC CALCULATOR IN JAVA

Building a calculator in Java is actually quite simple. You will use the skills learned in the past few lessons to make a calculator that can add, subtract, multiply, and divide two numbers.

  1. Install WindowBuilder

    • In order to make building windows even easier, we will install a plugin called WindowBuilder.
    • Locate HELP -> INSTALL NEW SOFTWARE.
    • In the "Work With" field, enter the following URL:
      http://download.eclipse.org/windowbuilder/WB/integration/4.6/
      
    • Select WindowBuilder, then click next.
    • Click Finish
    • Restart Eclipse
  2. Create a new project:

    • FILE -> NEW -> Java Project
    • Name the projects something relevant. I named mine "BasicCalculator".
    • Finish.
  3. Create a new package:

    • On the navigation view, open your project
    • Right click on the "src" (source) folder
    • Locate NEW -> PACKAGE
    • Name the package something relevant. I named mine "calculator".
  4. Create a WindowBuilder JFrame class:

    • Right click on your package
    • Locate NEW -> OTHER
    • Locate WindowBuilder -> Swing Designer -> JFrame.
    • Next
    • Name it something relevant. I named mine "Caluclator".
  5. Adding a layout:

    • This is simple since we will only be using an absolute layout.
    • When you open your newly added class, a lot of code will already be generated.
    • Your main class should already be created with a lot of extra code inside. You shouldn't need to change any of this code.
    • At the bottom of the edit window, there should be Source and Design tabs. Select Design.
    • Under the items palette, click on the "Absolute Layout", and add it to the frame.
    • It will not look like anything happened, but you have added a layout.
  6. Adding items to WindowBuilder:

    • This is done the same way as adding a layout.
    • Find an item on the palette, say, a TextField, and add it to your frame.
    • Under the Properties menu, you can change item options such as text size, font, etc.
    • Make sure to rename the "Variable" name to something you will remember.
  7. Building your calculator:

    • These next few steps will mostly be done on your own. See if you can create a JFrame will all of the required elements to look like the one below. Have fun with it and move things wherever you want.

    • The circular selectors are "JRadioButton"s, comparable to a checkbox.
  8. Adding Logic:

    • Switch back to the source view. A lot more code should have been added, you shouldn't need to modify most of it.
    • Add an Action Listener to your calculate button, under where WindowBuilder defined it in the constructor. (Yours may be named different):

      calc.addActionListener\(new ActionListener\(\) {
      
           @Override
           public void actionPerformed(ActionEvent e) {
      
           }
      
      });
      
    • This should look familiar as you have done this in the previous lessons.

    • Now lets create some public float variables to store your first and second number, and your output. (Remember these go ABOVE your main method)
      public static float input1 = 0.0f;
      public static float input2 = 0.0f;
      public static float output = 0.0f;
      
    • We use floats to more accurately calculate as well as allow for decimals. You could also use doubles, however floats are more often used in this situation.
    • Now we need to add some logic that will read input 1 and 2 and calculate them based on which radio button is selected.
    • Under your calculate button's action performed, add some code that parses the text to a float and stores that data in your input variables.
       input1 = Float.parseFloat(inputText1.getText());    
       input2 = Float.parseFloat(inputText2.getText());
      
    • This method can cause errors. If a non-numeric character is entered in either box, your program will crash. There is a fix for this however it is a bit out of the scope of this lesson. So dont input letters...
    • Now lets do some basic if statement logic based on the .isSelected() function of your radio buttons.
      if(add.isSelected()) output = input1 + input2;            // Sets output to sum
      if(sub.isSelected()) output = input1 - input2;            // Sets output to difference
      if(dev.isSelected()) output = input1 / input2;            // Sets output to quotient
      if(mul.isSelected()) output = input1 * input2;            // Sets output to product
      
    • Great! On Calculate, your output will be set to the calculated output of your choice.
    • In order for your output to be set in your window, we need to set the text of your result textField to the String equivalant of your output variable.
      answer.setText(Float.toString(output));
      
    • Test your app.
  9. Fixing other things:

    • Cool, your calculator is working, but there are still some issues with it.
    • You can edit the result field
    • And you can select multiple operators.
    • We will fix that now.
    • In order to keep from editing your result field, we need to set a parameter to disable editing.
    • Set editing to false under your result field code.
      answer.setEditable(false);
      
    • Tada! Now you cant edit your answer.
    • Now lets fix the issue of selecting multiple radio buttons.
    • We need to add an action event to each of our buttons. Refer to previous code to see how to add logic.
    • Under each of your buttons, use the .setSelected(boolean) function to set the other operators to false when clicked.

      add.addActionListener\(new ActionListener\(\) {
      
         @Override
         public void actionPerformed(ActionEvent e) {
             sub.setSelected(false);
             dev.setSelected(false);
             mul.setSelected(false);
         }
      
      });
      
    • Dont forget to modify these to make sense in each operator. Such as switch sub to add when in the sub radio button.

    • Test your app.

    • Congratulations! You have completed your first functioning calculator application in java! :D

results matching ""

    No results matching ""