Calculator 2.0



Instructions:  1. To enter input from the keyboard, click on the text field.  2. Use SHIFT+C to clear all entries.
3.  Use SHIFT+S for the square root.

 

Complete Source Code

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


/* This program represents my first attempt to use Swing components like JMenu, JTextField, JButton, and JLabel.  I have implemented both mouse and keyboard functionality.  I encountered some bugs that I have been unable to fix so far.  For example, if an operator has been chosen, the user MUST enter a numerical value immediately following this selection. Secondly, the square root button cannot be pressed while a computation is in progress (that is, after an operator has been chosen but before the equals button has been pressed). There is some inaccuracy with regards to how the computer handles decimal values (simple operations like 3.8-0.1 are evaluated as 3.69 instead of 3.7). And lastly, the user must click on the text field each time to give it the input focus for key events because the input focus is lost whenever the user clicks outside the text field. */


public class Calculator2 {


   private static JFrame myFrame;
   private static JMenuBar menuBar;
   private static JMenu file;
   private static JMenu theme;
   private static JMenu help;
   private static JMenuItem exit;
   private static JMenuItem red;
   private static JMenuItem blue;
   private static JMenuItem green;
   private static JMenuItem about;
   private static JPanel myPanel;
   private static MenuListener menuListener;
   private static FieldListener fieldListener;
   private static ButtonListener buttonListener;
   private static JTextField field;
   private static JButton[] button;
   private static JButton DOT, CLEAR, SQUARE_ROOT, EQUALS;
   private static JLabel copyright;
   private static String message;
   private static double input, result;
   private static int operator;
   private static boolean operatorPressed;

   public static class MenuListener implements ActionListener {

      public void actionPerformed(ActionEvent e) {

         Object source = e.getSource();

         if (source == exit) System.exit(0);

         else if (source == red) {

            myPanel.setBackground(new Color(255,200,200));
            copyright.setForeground(new Color(150,0,0));

         }

         else if (source == green) {

            myPanel.setBackground(new Color(200,255,200));
            copyright.setForeground(new Color(0,150,0));

         }

         else if (source == blue) {

            myPanel.setBackground(new Color(200,200,255));
            copyright.setForeground(new Color(0,0,150));

         }

         else if (source == about) JOptionPane.showMessageDialog(myPanel,message);

      }

   }

   public static class FieldListener implements KeyListener {

      public void keyPressed(KeyEvent e) {

         if (e.getKeyCode() == KeyEvent.VK_ENTER) button[17].doClick(100);

      }

      public void keyReleased(KeyEvent e) {}

      public void keyTyped(KeyEvent e) {

         for (int i = 0; i < 10; i++) {

            if (e.getKeyChar() == Character.forDigit(i,10)) button[i].doClick(100);

         }

         if (e.getKeyChar() == '.') button[10].doClick(100);
         if (e.getKeyChar() == '/') button[11].doClick(100);
         if (e.getKeyChar() == '*') button[12].doClick(100);
         if (e.getKeyChar() == '-') button[13].doClick(100);
         if (e.getKeyChar() == '+') button[14].doClick(100);
         if (e.getKeyChar() == 'C') button[15].doClick(100);
         if (e.getKeyChar() == 'S') button[16].doClick(100);
         if (e.getKeyChar() == '=') button[17].doClick(100);

      }

   }

   public static class ButtonListener implements ActionListener {

      public void actionPerformed(ActionEvent e) {

         Object source = e.getSource();

         for (int i = 0; i < 10; i++) {

            if (source == button[i] && field.getText().length() < 20) {

               if (input == 0 && !field.getText().equals("0.")) field.setText(Integer.toString(i));
               else field.setText(field.getText() + Integer.toString(i));

               input = Double.parseDouble(field.getText());
               if (!operatorPressed) result = input;

            }

         }

         for (int i = 1; i <= 4; i++) {

            if (source == button[i+10]) {

               if (operatorPressed) updateResult();
               operator = i;
               operatorPressed = true;
               input = 0;

            }

         }

         if (source == DOT) {

            if (input != 0 && !isDotPressed()) field.setText(field.getText() + ".");
            else if (input == 0) field.setText("0.");

         }

         else if (source == CLEAR) {

            input = 0;
            result = 0;
            operator = 0;
            operatorPressed = false;
            field.setText("0");

         }

         else if (source == SQUARE_ROOT) {

            result = Math.sqrt(result);

            if ((int)result - result == 0) field.setText(Integer.toString((int)result));
            else field.setText(Double.toString(result));

            input = 0;

         }

         else if (source == EQUALS) {

            updateResult();
            operatorPressed = false;
            operator = 0;
            input = 0;

         }

      }

      public void updateResult() {

         if (operator == 1) result /= input;
         else if (operator == 2) result *= input;
         else if (operator == 3) result -= input;
         else if (operator == 4) result += input;

         if ((int)result - result == 0) field.setText(Integer.toString((int)result));
         else field.setText(Double.toString(result));

      }

      public boolean isDotPressed() {

         for (int i = 0; i < field.getText().length(); i++) {

            if (field.getText().charAt(i) == '.') return true;

         }

         return false;

      }

   }

   public static void main(String[] args) {

      myFrame = new JFrame("Calculator 2.0");
      menuBar = new JMenuBar();
      file = new JMenu("File");
      theme = new JMenu("Theme");
      help = new JMenu("Help");
      exit = new JMenuItem("Exit");
      red = new JMenuItem("Red");
      green = new JMenuItem("Green");
      blue = new JMenuItem("Blue");
      about = new JMenuItem("About");
      myPanel = new JPanel();
      menuListener = new MenuListener();
      fieldListener = new FieldListener();
      buttonListener = new ButtonListener();
      field = new JTextField();
      button = new JButton[18];
      copyright = new JLabel("\u00A9 2011 by Dilip Muthukrishnan", JLabel.CENTER);
      message = "Calculator 2.0 was written using the Java programming language.\n" +
                "It uses a Swing interface by providing basic JMenu, JTextField,\n" +
                "and JButton functionality. This entire program was coded from\n" +
                "scratch using Notepad.";
      input = 0;
      result = 0;
      operator = 0;
      operatorPressed = false;

      exit.addActionListener(menuListener);
      red.addActionListener(menuListener);
      green.addActionListener(menuListener);
      blue.addActionListener(menuListener);
      blue.setSelected(true);
      about.addActionListener(menuListener);
      file.add(exit);
      theme.add(red);
      theme.add(green);
      theme.add(blue);
      help.add(about);
      menuBar.add(file);
      menuBar.add(theme);
      menuBar.add(help);

      myPanel.setBackground(new Color(200,200,255));
      myPanel.setLayout(null);
      myPanel.add(field);
      myPanel.add(copyright);

      field.addKeyListener(fieldListener);
      field.setBounds(15,15,220,40);
      field.setMargin(new Insets(5,5,5,5));
      field.setBackground(Color.WHITE);
      field.setFont(new Font("TimesRoman",Font.PLAIN,18));
      field.setHorizontalAlignment(field.RIGHT);
      field.setEditable(false);
      field.setText("0");

      for (int i = 0; i < 18; i++) {

         button[i] = new JButton();
         button[i].setMargin(new Insets(0,0,0,0));
         if (i < 10) button[i].setText(Integer.toString(i));
         button[i].addActionListener(buttonListener);
         myPanel.add(button[i]);

      }

      DOT = button[10];
      CLEAR = button[15];
      SQUARE_ROOT = button[16];
      EQUALS = button[17];

      DOT.setText(".");
      button[11].setText("/");
      button[12].setText("*");
      button[13].setText("-");
      button[14].setText("+");
      CLEAR.setText("C");
      SQUARE_ROOT.setText("\u221A");
      EQUALS.setText("=");

      button[0].setBounds(15,185,85,30);
      button[1].setBounds(15,150,40,30);
      button[2].setBounds(60,150,40,30);
      button[3].setBounds(105,150,40,30);
      button[4].setBounds(15,115,40,30);
      button[5].setBounds(60,115,40,30);
      button[6].setBounds(105,115,40,30);
      button[7].setBounds(15,80,40,30);
      button[8].setBounds(60,80,40,30);
      button[9].setBounds(105,80,40,30);

      button[11].setBounds(150,80,40,30);
      button[12].setBounds(150,115,40,30);
      button[13].setBounds(150,150,40,30);
      button[14].setBounds(150,185,40,30);

      DOT.setBounds(105,185,40,30);
      CLEAR.setBounds(195,80,40,30);
      SQUARE_ROOT.setBounds(195,115,40,30);
      EQUALS.setBounds(195,150,40,65);

      copyright.setForeground(new Color(0,0,150));
      copyright.setBounds(15,240,220,30);

      myFrame.setJMenuBar(menuBar);
      myFrame.setContentPane(myPanel);
      myFrame.setLocation(100,100);
      myFrame.setSize(254,325);
      myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      myFrame.setResizable(false);
      myFrame.setVisible(true);

   }


}