Java Snippet

Java Project - Calculator

This calculator application was built together with the calculator applications written in vb  java/applet.

They all look and operate similarly, however, I've only just corrected a "banker's rounding" discrepancy in both this and the java/applet programs. At the time of writing (30 May 2003) there appear to be no side-effects from the changes made.

Try the java/applet version here (written without swing components)

                                                               use mouse or keyboard
                                         Shortcut keys Cancel - C, Clear All - A, Clr List - L

Your browser does Not support Java Applets.

Click to see versions in     vb    java/applet

 

Java/Swing Code

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
 
class Calculator extends JFrame implements ActionListener, ItemListener,
                                KeyListener, MouseListener, FocusListener
{
  JList list;
  DefaultListModel myListModel;
  JScrollPane listScroll;
  JRadioButton radioBtn[] = new JRadioButton[6];
  ButtonGroup radioGrp;
  JLabel radioLbl[] = new JLabel[7];
  JButton btn[] = new JButton[20];
  JTextField txtFld;
 
  boolean calculated;
  String lastEntry;
  String currentTotal;
  int lastOperator = 1;   //1 for +, 2 for -, 3 for =,4 for x, 5 for
  int decimalPlaces = 2;
  DecimalFormat df;
 
  public static void main(String args[])
  {
    Calculator calc = new Calculator();
  }
 
  public Calculator()
  {
    super("Calculator");
    setSize(600,350);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    buildGUI();
    pack();
    setResizable(false);
    setVisible(true);
    setDecimalPlaces();
    clearAll();
    setTheFocus();
  }
 
  private void cancel()
  {
    txtFld.setText(currentTotal);
    calculated = true;
    setTheFocus();
  }
 
  private void clearAll()
  {
    addToJList("<Clr>  ");
    txtFld.setText(df.format(Double.parseDouble("0")));
    calculated = true;
    lastEntry = df.format(Double.parseDouble("0"));
    currentTotal = df.format(Double.parseDouble("0"));
    setTheFocus();
  }
 
  private void clearList()
  {
    myListModel.clear();
    addToJList("<Clr>  ");
    setTheFocus();
  }
 
  private void setDecimalPlaces()
  {
    String decimals[] = {"0","0.0","0.00","0.000","0.0000","0.00000"};
    df = new DecimalFormat(decimals[decimalPlaces]);
  }
 
  private void setTheFocus()
  {
    txtFld.setCaretPosition(txtFld.getText().length());
    txtFld.grabFocus();
  }
 
  private void addToJList(String number)
  {
    int extra = 0;
    if(number.length() > 5) extra = number.length()/2-1;
    if(number.length() > 7) extra += (number.length()-7)/2;
    for(int i = 0; i < 55-number.length()-extra; i++)
    {
      number = " " + number;
    }
 
    myListModel.addElement(number);
    list.setModel(myListModel);
    list.setSelectedIndex(myListModel.getSize()-1);
    list.ensureIndexIsVisible(myListModel.getSize()-1);
    setTheFocus();
  }
//------------------------------------------VALIDATE/KEYBOARD ACTIONS
  private boolean validKey(char keyPressed)
  {
 
    boolean valid = false;
 
    if(keyPressed == '0' || keyPressed == '1' || keyPressed == '2' ||
       keyPressed == '3' || keyPressed == '4' || keyPressed == '5' ||
       keyPressed == '6' || keyPressed == '7' || keyPressed == '8' ||
       keyPressed == '9' || keyPressed == '.')
    {
      valid = true;
 
      if(calculated)
      {
        txtFld.setText("");
        calculated = false;
      }
      if((keyPressed == '.' && txtFld.getText().indexOf(".") > -1) ||
        ! checkLength())
      {
        valid = false;
      }
    }
    else if(keyPressed == '+') addNumber();
    else if(keyPressed == '-') subtractNumber();
    else if(keyPressed == '*') multiplyNumber(false);
    else if(keyPressed == '/') divideNumber(false);
    else if(keyPressed == KeyEvent.VK_ENTER) equals();
    else if(keyPressed == 'C' || keyPressed == 'c') cancel();
    else if(keyPressed == 'A' || keyPressed == 'a') clearAll();
    else if(keyPressed == 'L' || keyPressed == 'l') clearList();
    return valid;
  }
 
  private boolean checkLength()
  {
    boolean OK = true;
    if((txtFld.getText().indexOf(".") > -1 &&
        txtFld.getText().length() > 12) ||
      (txtFld.getText().indexOf(".") < 0 &&
        txtFld.getText().length() > 11))
    {
       OK = false;
    }
    return OK;
  }
//--------------------------------------------------ACTIONS FOR + - * / =
  private void addNumber()
  {
    double decNumber = Math.abs(Double.parseDouble(
            calculated? lastEntry:txtFld.getText()));
    String formattedNumber = df.format(decNumber);
    currentTotal = df.format(Double.parseDouble(currentTotal)+decNumber);
    txtFld.setText(currentTotal);
    addToJList(formattedNumber + " +");
    lastEntry = formattedNumber;
    calculated = true;
    lastOperator = 1;
    setTheFocus();
  }
 
  private void subtractNumber()
  {
    double decNumber = Math.abs(Double.parseDouble(
            calculated? lastEntry:txtFld.getText()));
    String formattedNumber = df.format(decNumber);
    currentTotal = df.format(Double.parseDouble(currentTotal)-decNumber);
    txtFld.setText(currentTotal);
    addToJList(formattedNumber + " -");
    lastEntry = formattedNumber;
    calculated = true;
    lastOperator = 2;
    setTheFocus();
  }
 
  private void multiplyNumber(boolean fromEqualsOperater)
  {
    boolean zeroNumber = false;
    double decNumber = Double.parseDouble(txtFld.getText());
    String formattedNumber = String.valueOf(decNumber);
    if(lastOperator < 4)
    {
      currentTotal = lastEntry = formattedNumber;
    }
    else if(calculated)
    {
      currentTotal = df.format(Double.parseDouble(currentTotal) *
                                  Double.parseDouble(lastEntry));
    }
    else if(lastOperator == 5)
    {
      currentTotal = df.format(((long)((Double.parseDouble(currentTotal) / decNumber) *
                        Math.pow(10,decimalPlaces) + 0.5))/Math.pow(10,decimalPlaces));
    }
    else
    {
      currentTotal = df.format(((long)((Double.parseDouble(currentTotal) * decNumber) *
                        Math.pow(10,decimalPlaces) + 0.5))/Math.pow(10,decimalPlaces));
    }
 
    txtFld.setText(currentTotal);
    if((int) decNumber - decNumber == 0)
    {
      formattedNumber = formattedNumber.substring(0,formattedNumber.lastIndexOf("."));
      zeroNumber = true;
    }
    if(! fromEqualsOperater)
    {
      addToJList(formattedNumber + " x");
    }
    else if(zeroNumber)
    {
      addToJList(formattedNumber + " ");
    }
    else
    {
      addToJList(formattedNumber + "  ");
    }
    calculated = true;
    lastOperator = 4;
    setTheFocus();
  }
 
  private void divideNumber(boolean fromEqualsOperater)
  {
    boolean zeroNumber = false;
    double decNumber = Double.parseDouble(txtFld.getText());
    String formattedNumber = String.valueOf(decNumber);
    if(lastOperator < 4)
    {
      currentTotal = lastEntry = formattedNumber;
    }
    else if(calculated)
    {
      currentTotal = df.format(Double.parseDouble(currentTotal) /
                                  Double.parseDouble(lastEntry));
    }
    else if(lastOperator == 4)
    {
      currentTotal = df.format(((long)((Double.parseDouble(currentTotal) * decNumber) *
                         Math.pow(10,decimalPlaces) + 0.5))/Math.pow(10,decimalPlaces));
    }
    else
    {
      currentTotal = df.format(((long)((Double.parseDouble(currentTotal) / decNumber) *
                        Math.pow(10,decimalPlaces) + 0.5))/Math.pow(10,decimalPlaces));
    }
 
    txtFld.setText(currentTotal);
    if((int) decNumber - decNumber == 0)
    {
      formattedNumber = formattedNumber.substring(0,formattedNumber.lastIndexOf("."));
      zeroNumber = true;
    }
    if(! fromEqualsOperater)
    {
      addToJList(formattedNumber + " ");
    }
    else if(zeroNumber)
    {
      addToJList(formattedNumber + " ");
    }
    else
    {
      addToJList(formattedNumber + "  ");
    }
    calculated = true;
    lastOperator = 5;
    setTheFocus();
  }
 
  private void equals()
  {
    if(lastOperator != 3)
    {
      if(! calculated && lastOperator < 3) addNumber();
      if(! calculated && lastOperator == 4) multiplyNumber(true);
      if(! calculated && lastOperator == 5) divideNumber(true);
      addToJList(currentTotal + " =");
      addToJList("...  ");
      lastEntry = currentTotal;
      currentTotal = df.format(0.0);
      calculated = true;
      lastOperator = 3;
      setTheFocus();
    }
    else
    {
      clearAll();
    }
  }
//----------------------------------------------------KEYPAD ACTIONS
  public void actionPerformed(ActionEvent ae)
  {
    for(int i=0; i<=11; i++)
    {
      if(ae.getSource() == btn[i])
      {
        if(calculated)
        {
          txtFld.setText("");
          calculated = false;
        }
        if(ae.getSource() == btn[11] && txtFld.getText().indexOf(".") > -1) break;
        if(checkLength()) txtFld.setText(txtFld.getText()+btn[i].getText());
        break;
      }
    }
 
    if(ae.getSource() == btn[12]) multiplyNumber(false);
    else if(ae.getSource() == btn[13]) divideNumber(false);
    else if(ae.getSource() == btn[14]) subtractNumber();
    else if(ae.getSource() == btn[15]) addNumber();
    else if(ae.getSource() == btn[19]) equals();
    else if(ae.getSource() == btn[16]) cancel();
    else if(ae.getSource() == btn[17]) clearAll();
    else if(ae.getSource() == btn[18]) clearList();
    setTheFocus();
  }
 
  public void itemStateChanged(ItemEvent ie){}
  public void keyTyped(KeyEvent kb){}
  public void keyPressed(KeyEvent kb){}
  public void keyReleased(KeyEvent kb){}
  public void focusGained(FocusEvent fe){}
  public void focusLost(FocusEvent fe){}
//------------------------------------------------MOUSE ACTIONS
  public void mouseClicked(MouseEvent me)
  {
    for(int i=0; i<radioBtn.length; i++)
    {
      if(me.getSource() == radioBtn[i])
      {
        radioBtn[i].setSelected(true);
        decimalPlaces = i;
        setDecimalPlaces();
        clearAll();
        break;
      }
    }
    setTheFocus();
  }
 
  public void mousePressed(MouseEvent me)
  {
    setTheFocus();
  }
 
  public void mouseReleased(MouseEvent me)
  {
    setTheFocus();
  }
 
  public void mouseEntered(MouseEvent me){}
  public void mouseExited(MouseEvent me){}
//-----------------------------------------------------------------------
  private void buildGUI()                    //BUILD THE GUI
  {
    Container cp = getContentPane();
    cp.setLayout(new BorderLayout());
 
    Panel leftPanel = new Panel();         //ADD JLIST/SCOLLPANE
    leftPanel.addMouseListener(this);
    list = new JList();
    list.setFont(new Font("Courier New",Font.PLAIN,12));
    list.addMouseListener(this);
    myListModel = new DefaultListModel();
    list.setVisibleRowCount(14);
    listScroll = new JScrollPane (list);
    leftPanel.add(listScroll);
    cp.add(leftPanel,BorderLayout.WEST);
 
    Panel rightPanel = new Panel();
    rightPanel.setLayout(new BorderLayout());
    rightPanel.addMouseListener(this);
 
    txtFld  = new JTextField("0.00");              //ADD TEXTFIELD
    txtFld.setHorizontalAlignment(JTextField.RIGHT);
    txtFld.setFont(new Font("Helvetica",Font.BOLD, 30));
    txtFld.addKeyListener(this);
    txtFld.addKeyListener(new KeyAdapter()
    {
      public void keyTyped(KeyEvent ke)
      {
        char keyChar = ke.getKeyChar();
        if(! validKey(keyChar)) ke.consume();
      }
    });
    txtFld.addFocusListener(this);
    txtFld.addMouseListener(this);
    txtFld.hasFocus();
    rightPanel.add(txtFld,BorderLayout.NORTH);
 
    radioGrp = new ButtonGroup();            //ADD OPTIONBUTTONS
    Panel decimals = new Panel();
    decimals.setLayout(new FlowLayout());
    decimals.addMouseListener(this);
    for(int i=0; i< radioBtn.length; i++)
    {
      radioBtn[i] = new JRadioButton();
      radioBtn[i].addItemListener(this);
      radioBtn[i].addMouseListener(this);
      radioGrp.add(radioBtn[i]);
      radioLbl[i] = new JLabel(String.valueOf(i));
    }
    radioBtn[2].setSelected(true);
    radioLbl[6] = new JLabel("Decimals       ");
    decimals.add(radioLbl[6]);
    for(int i = 0; i < radioBtn.length; i++)
    {
      decimals.add(radioLbl[i]);
      decimals.add(radioBtn[i]);
    }
    rightPanel.add(decimals,BorderLayout.CENTER);
 
    Panel numPad = new Panel();                   //ADD KEYPAD
    numPad.setLayout(new GridLayout(5,4));
    for(int i = 0; i < btn.length; i++)
    {
      btn[i] = new JButton();
      btn[i].addActionListener(this);
      btn[i].setFont(new Font("Serif",Font.BOLD, 18));
      if(i<10) btn[i].setText(String.valueOf(i));
      else if(i == 10) btn[i].setText("00");
      else if(i == 11) btn[i].setText(".");
      else if(i == 12) btn[i].setText("x");
      else if(i == 13) btn[i].setText("");
      else if(i == 14) btn[i].setText("-");
      else if(i == 15) btn[i].setText("+");
      else if(i == 16) btn[i].setText("Cancel");
      else if(i == 17) btn[i].setText("Clr All");
      else if(i == 18) btn[i].setText("CIr List");
      else if(i == 19) btn[i].setText("=");
    }
    btn[12].setFont(new Font("Serif",Font.PLAIN, 18));
    btn[16].setFont(new Font("Serif",Font.BOLD, 11));
    btn[17].setFont(new Font("Serif",Font.BOLD, 11));
    btn[18].setFont(new Font("Serif",Font.BOLD, 11));
    btn[16].setMnemonic(KeyEvent.VK_C);
    btn[17].setMnemonic(KeyEvent.VK_A);
    btn[18].setMnemonic(KeyEvent.VK_L);
    numPad.add(btn[16]);
    numPad.add(btn[17]);
    numPad.add(btn[18]);
    numPad.add(btn[12]);
    numPad.add(btn[7]);
    numPad.add(btn[8]);
    numPad.add(btn[9]);
    numPad.add(btn[13]);
    numPad.add(btn[4]);
    numPad.add(btn[5]);
    numPad.add(btn[6]);
    numPad.add(btn[14]);
    numPad.add(btn[1]);
    numPad.add(btn[2]);
    numPad.add(btn[3]);
    numPad.add(btn[15]);
    numPad.add(btn[0]);
    numPad.add(btn[10]);
    numPad.add(btn[11]);
    numPad.add(btn[19]);
    rightPanel.add(numPad,BorderLayout.SOUTH);
 
    cp.add(rightPanel,BorderLayout.EAST);
    setContentPane(cp);
  }
 
  public void setVisible(boolean visible)   //CENTER SCREEN
  {
    if(visible)
    {
      Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
      setLocation((dim.width - getWidth())/2, (dim.height - getHeight())/2);
    }
    super.setVisible(visible);
  }
}


back    top    main page    vb snippets page      java snippets page     vbscript snippets page   email    Page last modified