import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import ETextField;
public class AwtCalc extends java.applet.Applet implements ActionListener
{
private Button[] buttons = new Button[19];
private String[] buttonText = { " 1 ", " 2 ", " 3 ", " + ", " - ",
" 4 ", " 5 ", " 6 ", " x ", " / ",
" 7 ", " 8 ", " 9 ", "^ ", "sqrt",
" C ", " 0 ", " . ", " = "};
private ETextField result; // Calculator display screen
private String input = ""; // stores user input
private Label label;
private Color forecolor, // Calculator foreground color
backcolor, // Calculator background color
fieldcolor; // the display screen's color
private Font font,
buttonfont;
private int oper = 0, // stores the integer constants representing
oldoper = 0, // the operators
newoper = 0;
private double answer,
num1 = 0.0,
num2 = 0.0,
num3 = 0.0;
private final int ADD=1, // integer constants representing operators
SUB = 2,
MULT = 3,
DIVI = 4,
POW = 5,
SQRT = 6;
private boolean firstpress = true, //determines first button press
morenums = false, //"" if more numbers are being pressed
equals = false, //"" if equal button has been pressed
clearscreen = false, //clears screen
decnumber = false, //"" if a user entered a float
doubleclick = false; //"" if mouse was doubleclicked
public void init() {
font = new Font( "Courier", Font.ITALIC, 10 );
buttonfont = new Font( "Courier", Font.PLAIN, 12 );
setBackground( Color.lightGray );
//initialize colors
result = new ETextField( 125, 18 );
label = new Label( "AWT Calculator" );
setLayout( new FlowLayout() );
add( result );
add( label );
//initialize and add buttons
for ( int i = 0; i < 19; i++ ) {
buttons[i] = new Button( buttonText[i] );
buttons[i].setFont( buttonfont );
buttons[i].addActionListener( this );
if ( i <= 2 )
add( buttons[i] );
else if ( i >= 3 && i <= 7)
add( buttons[i] );
else if ( i >=8 && i <= 12 )
add( buttons[i] );
else if ( i >= 13 && i <= 17 )
add( buttons[i] );
else
add( buttons[i] );
if ( i == 2 )
add( new Label( " " ) );
else if ( i == 7 )
add( new Label( " " ) );
else if ( i == 12 )
add( new Label( " " ) );
else if ( i == 17 )
add( new Label( " " ) );
}
buttons[15].setForeground( Color.red );
result.setBackground( Color.white );
label.setFont( font );
}
//==============================================================================
// Interface method that determines which button was pressed then determines
// the appropriate action.
//==============================================================================
public void actionPerformed( ActionEvent e )
{
// "if" block is not entered if the button is an operator
if ( e.getSource() != buttons[3] && e.getSource() != buttons[4]
&& e.getSource() != buttons[8] && e.getSource() != buttons[9]
&& e.getSource() != buttons[13] && e.getSource() != buttons[14]
&& e.getSource() != buttons[15] && e.getSource() != buttons[18] ) {
if ( clearscreen ) { // clears screen if user enters number before an
clearScreen(); // operator after pressing equals
clearscreen = false;
}
if ( e.getSource() == buttons[0] ) {
input += "1"; // concoctenate "1" to input
result.setText( input );
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[1] ) {
input += "2"; // concoctenate "2" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[2] ) {
input += "3"; // concoctenate "3" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[5] ) {
input += "4"; // concoctenate "4" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[6] ) {
input += "5"; // concoctenate "5" to input
showAnswer( input );
} // end if
else if ( e.getSource() == buttons[7] ) {
input += "6"; // concoctenate "6" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[10] ) {
input += "7"; // concoctenate "7" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[11] ) {
input += "8"; // concoctenate "8" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[12] ) {
input += "9"; // concoctenate "9" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[16] ) {
input += "0"; // concoctenate "0" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[17] ) {
if ( decnumber == false ) {
decnumber = true;
input += ".0"; // concoctenate "." to input
showAnswer( input );
}
}
} // end if
// check if user entered the addition operator
if ( e.getSource() == buttons[3] ) {
clearscreen = false;
decnumber = false;
oper = ADD; // oper is set to addition
clickCheck( input ); // checks if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end if
// check if user entered the subtraction operator
else if (e.getSource() == buttons[4] ) {
clearscreen = false;
decnumber = false;
oper = SUB; // oper is set to subtraction
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the multiplication operator
else if (e.getSource() == buttons[8] ) {
clearscreen = false;
decnumber = false;
oper = MULT; // oper is set to multiplication
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} //end else if
// check if user entered the divide operator
else if (e.getSource() == buttons[9] ) {
clearscreen = false;
decnumber = false;
oper = DIVI; // oper is set to divide
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the exponential operator
else if ( e.getSource() == buttons[13] ) {
clearscreen = false;
decnumber = false;
oper = POW; // oper is set to exponential
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the square root operator
else if ( e.getSource() == buttons[14] ) {
clearscreen = false;
oper = SQRT; // oper is set to square root
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the clear operator
if (e.getSource() == buttons[15] ) {
clearScreen();
} // end if
// check if user entered the equal operator
if (e.getSource() == buttons[18] ) {
equals = true;
clearscreen = true;
clickCheck( input ); //check if user double-clicked
if ( doubleclick == false )
processNumbers(); //continue to process numbers if
input = Double.toString( answer ); //if no double-click
} // end if
} // end actionPerformed()
//==============================================================================
//Method processNumbers is where processes the numbers inputed by the user
//==============================================================================
public void processNumbers() {
// the program enters this "if" block when an operator is pressed for the
// first time
if ( firstpress ) {
if ( equals ) {
num1 = answer; //answer is stored in num1 if user enters equal operator
equals = false; // equals is set to false to allow additional input
} // end if
else
num1 = Double.valueOf( input ).doubleValue(); // converts a string number to double
oldoper = oper; // store current operator to oldoper
// if operator is square root, calculation and output is done immediately
if ( oper == SQRT ) {
answer = calculate( oldoper, num1, 0.0 );
showAnswer( Double.toString( answer ) );
morenums = true;
}
firstpress = false; // no longer the first operator
} // end if
// "if" block is entered if now more than two numbers are being entered to
// be calculated
else if ( !morenums ) {
num2 = Double.valueOf( input ).doubleValue(); //converts second num to double
answer = calculate( oldoper, num1, num2 ); //calculate num1 and num2 with
showAnswer( Double.toString( answer) ); //the past operator
newoper = oper; //store current operator to
//new oper
if ( !equals )
morenums = true; //tells program that more than two numbers have
else { //entered
morenums = false; //if equal operator is pressed, firstpress
firstpress = true; //returns to true
} // end else
} // end if
// if more than two numbers are being inputted to calculate, this "if" block
// is accessed
else if (morenums) {
if ( equals ) {
newoper = oper;
morenums = false;
firstpress = true; // if equals is pressed set firstpress to false
} // end if
num3 = Double.valueOf( input ).doubleValue();
answer = calculate( newoper, answer, num3 );
showAnswer( Double.toString(answer) );
newoper = oper;
} // end else if
} // end processNumbers()
//==============================================================================
//Method calculate determines which operator was entered and calculates
//two numbers depending on the operator pressed
//==============================================================================
public double calculate( int oper, double number1, double number2 )
{
double answer = 0.0;
switch( oper ) {
case ADD:
answer = number1 + number2;
break;
case SUB:
answer = number1 - number2;
break;
case MULT:
answer = number1 * number2;
break;
case DIVI:
answer = number1 / number2;
break;
case POW:
answer = Math.pow( number1, number2 );
break;
case SQRT:
answer = Math.sqrt( number1 );
break;
} // end switch
return answer;
} // end calculate()
//==============================================================================
//Method showAnswer outputs the results in the calculators displays screen
//==============================================================================
public void showAnswer( String s )
{
double answer;
answer = Double.valueOf(s).doubleValue();
if ( decnumber )
result.setText( Double.toString(answer) );
else
result.setText( s ); //all output are displayed as integers at start
} // end showAnswer
//==============================================================================
//Method clickCheck determines if the user double clicked and returns a boolean
//value. If doubleclick is true, the program ignores the input
//==============================================================================
public boolean clickCheck( String s ) {
if ( s == "" )
doubleclick = true;
else
doubleclick = false;
return doubleclick;
}
//==============================================================================
//Method clearScreen clears calculator display screen and sets variables to
//default.
//==============================================================================
public void clearScreen()
{
oper = 0; // reinitialize variables to default
input = "";
answer = 0;
decnumber = false;
morenums = false;
firstpress = true;
equals = false;
showAnswer( Integer.toString( (int)answer) );
}
public void paint( Graphics g )
{
//draw border
g.drawRect( 0, 0, size().width - 1, size().height - 1 );
g.drawLine( 0, 0, 0, size().height );
}
} // end program
Showing posts with label calculator. Show all posts
Showing posts with label calculator. Show all posts
Saturday, 23 July 2011
createting calculator on JAVA using awt classes
Monday, 11 April 2011
createting calculator on JAVA using awt classes
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import ETextField;
public class AwtCalc extends java.applet.Applet implements ActionListener
{
private Button[] buttons = new Button[19];
private String[] buttonText = { " 1 ", " 2 ", " 3 ", " + ", " - ",
" 4 ", " 5 ", " 6 ", " x ", " / ",
" 7 ", " 8 ", " 9 ", "^ ", "sqrt",
" C ", " 0 ", " . ", " = "};
private ETextField result; // Calculator display screen
private String input = ""; // stores user input
private Label label;
private Color forecolor, // Calculator foreground color
backcolor, // Calculator background color
fieldcolor; // the display screen's color
private Font font,
buttonfont;
private int oper = 0, // stores the integer constants representing
oldoper = 0, // the operators
newoper = 0;
private double answer,
num1 = 0.0,
num2 = 0.0,
num3 = 0.0;
private final int ADD=1, // integer constants representing operators
SUB = 2,
MULT = 3,
DIVI = 4,
POW = 5,
SQRT = 6;
private boolean firstpress = true, //determines first button press
morenums = false, //"" if more numbers are being pressed
equals = false, //"" if equal button has been pressed
clearscreen = false, //clears screen
decnumber = false, //"" if a user entered a float
doubleclick = false; //"" if mouse was doubleclicked
public void init() {
font = new Font( "Courier", Font.ITALIC, 10 );
buttonfont = new Font( "Courier", Font.PLAIN, 12 );
setBackground( Color.lightGray );
//initialize colors
result = new ETextField( 125, 18 );
label = new Label( "AWT Calculator" );
setLayout( new FlowLayout() );
add( result );
add( label );
//initialize and add buttons
for ( int i = 0; i < 19; i++ ) {
buttons[i] = new Button( buttonText[i] );
buttons[i].setFont( buttonfont );
buttons[i].addActionListener( this );
if ( i <= 2 )
add( buttons[i] );
else if ( i >= 3 && i <= 7)
add( buttons[i] );
else if ( i >=8 && i <= 12 )
add( buttons[i] );
else if ( i >= 13 && i <= 17 )
add( buttons[i] );
else
add( buttons[i] );
if ( i == 2 )
add( new Label( " " ) );
else if ( i == 7 )
add( new Label( " " ) );
else if ( i == 12 )
add( new Label( " " ) );
else if ( i == 17 )
add( new Label( " " ) );
}
buttons[15].setForeground( Color.red );
result.setBackground( Color.white );
label.setFont( font );
}
//==============================================================================
// Interface method that determines which button was pressed then determines
// the appropriate action.
//==============================================================================
public void actionPerformed( ActionEvent e )
{
// "if" block is not entered if the button is an operator
if ( e.getSource() != buttons[3] && e.getSource() != buttons[4]
&& e.getSource() != buttons[8] && e.getSource() != buttons[9]
&& e.getSource() != buttons[13] && e.getSource() != buttons[14]
&& e.getSource() != buttons[15] && e.getSource() != buttons[18] ) {
if ( clearscreen ) { // clears screen if user enters number before an
clearScreen(); // operator after pressing equals
clearscreen = false;
}
if ( e.getSource() == buttons[0] ) {
input += "1"; // concoctenate "1" to input
result.setText( input );
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[1] ) {
input += "2"; // concoctenate "2" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[2] ) {
input += "3"; // concoctenate "3" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[5] ) {
input += "4"; // concoctenate "4" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[6] ) {
input += "5"; // concoctenate "5" to input
showAnswer( input );
} // end if
else if ( e.getSource() == buttons[7] ) {
input += "6"; // concoctenate "6" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[10] ) {
input += "7"; // concoctenate "7" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[11] ) {
input += "8"; // concoctenate "8" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[12] ) {
input += "9"; // concoctenate "9" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[16] ) {
input += "0"; // concoctenate "0" to input
showAnswer( input );
} // end else if
else if ( e.getSource() == buttons[17] ) {
if ( decnumber == false ) {
decnumber = true;
input += ".0"; // concoctenate "." to input
showAnswer( input );
}
}
} // end if
// check if user entered the addition operator
if ( e.getSource() == buttons[3] ) {
clearscreen = false;
decnumber = false;
oper = ADD; // oper is set to addition
clickCheck( input ); // checks if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end if
// check if user entered the subtraction operator
else if (e.getSource() == buttons[4] ) {
clearscreen = false;
decnumber = false;
oper = SUB; // oper is set to subtraction
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the multiplication operator
else if (e.getSource() == buttons[8] ) {
clearscreen = false;
decnumber = false;
oper = MULT; // oper is set to multiplication
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} //end else if
// check if user entered the divide operator
else if (e.getSource() == buttons[9] ) {
clearscreen = false;
decnumber = false;
oper = DIVI; // oper is set to divide
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the exponential operator
else if ( e.getSource() == buttons[13] ) {
clearscreen = false;
decnumber = false;
oper = POW; // oper is set to exponential
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the square root operator
else if ( e.getSource() == buttons[14] ) {
clearscreen = false;
oper = SQRT; // oper is set to square root
clickCheck( input ); // check if user doubleclicked
if ( doubleclick == false )
processNumbers(); // if no double click continue to process
input = ""; // clear variable to store new input
} // end else if
// check if user entered the clear operator
if (e.getSource() == buttons[15] ) {
clearScreen();
} // end if
// check if user entered the equal operator
if (e.getSource() == buttons[18] ) {
equals = true;
clearscreen = true;
clickCheck( input ); //check if user double-clicked
if ( doubleclick == false )
processNumbers(); //continue to process numbers if
input = Double.toString( answer ); //if no double-click
} // end if
} // end actionPerformed()
//==============================================================================
//Method processNumbers is where processes the numbers inputed by the user
//==============================================================================
public void processNumbers() {
// the program enters this "if" block when an operator is pressed for the
// first time
if ( firstpress ) {
if ( equals ) {
num1 = answer; //answer is stored in num1 if user enters equal operator
equals = false; // equals is set to false to allow additional input
} // end if
else
num1 = Double.valueOf( input ).doubleValue(); // converts a string number to double
oldoper = oper; // store current operator to oldoper
// if operator is square root, calculation and output is done immediately
if ( oper == SQRT ) {
answer = calculate( oldoper, num1, 0.0 );
showAnswer( Double.toString( answer ) );
morenums = true;
}
firstpress = false; // no longer the first operator
} // end if
// "if" block is entered if now more than two numbers are being entered to
// be calculated
else if ( !morenums ) {
num2 = Double.valueOf( input ).doubleValue(); //converts second num to double
answer = calculate( oldoper, num1, num2 ); //calculate num1 and num2 with
showAnswer( Double.toString( answer) ); //the past operator
newoper = oper; //store current operator to
//new oper
if ( !equals )
morenums = true; //tells program that more than two numbers have
else { //entered
morenums = false; //if equal operator is pressed, firstpress
firstpress = true; //returns to true
} // end else
} // end if
// if more than two numbers are being inputted to calculate, this "if" block
// is accessed
else if (morenums) {
if ( equals ) {
newoper = oper;
morenums = false;
firstpress = true; // if equals is pressed set firstpress to false
} // end if
num3 = Double.valueOf( input ).doubleValue();
answer = calculate( newoper, answer, num3 );
showAnswer( Double.toString(answer) );
newoper = oper;
} // end else if
} // end processNumbers()
//==============================================================================
//Method calculate determines which operator was entered and calculates
//two numbers depending on the operator pressed
//==============================================================================
public double calculate( int oper, double number1, double number2 )
{
double answer = 0.0;
switch( oper ) {
case ADD:
answer = number1 + number2;
break;
case SUB:
answer = number1 - number2;
break;
case MULT:
answer = number1 * number2;
break;
case DIVI:
answer = number1 / number2;
break;
case POW:
answer = Math.pow( number1, number2 );
break;
case SQRT:
answer = Math.sqrt( number1 );
break;
} // end switch
return answer;
} // end calculate()
//==============================================================================
//Method showAnswer outputs the results in the calculators displays screen
//==============================================================================
public void showAnswer( String s )
{
double answer;
answer = Double.valueOf(s).doubleValue();
if ( decnumber )
result.setText( Double.toString(answer) );
else
result.setText( s ); //all output are displayed as integers at start
} // end showAnswer
//==============================================================================
//Method clickCheck determines if the user double clicked and returns a boolean
//value. If doubleclick is true, the program ignores the input
//==============================================================================
public boolean clickCheck( String s ) {
if ( s == "" )
doubleclick = true;
else
doubleclick = false;
return doubleclick;
}
//==============================================================================
//Method clearScreen clears calculator display screen and sets variables to
//default.
//==============================================================================
public void clearScreen()
{
oper = 0; // reinitialize variables to default
input = "";
answer = 0;
decnumber = false;
morenums = false;
firstpress = true;
equals = false;
showAnswer( Integer.toString( (int)answer) );
}
public void paint( Graphics g )
{
//draw border
g.drawRect( 0, 0, size().width - 1, size().height - 1 );
g.drawLine( 0, 0, 0, size().height );
}
} // end program
Tuesday, 29 March 2011
claculator on Java with "back space" and "calculation display"
/*
Title: Calculator App
Created: August 7, 2008
Author: Blmaster
Comments:
Wanted to see if I could make it.
Last Edited: August 20, 2008
Changes:
See Bottom of Code ||
*******************\/
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator implements ActionListener, ItemListener, KeyListener {
private final String VERSION = "4.0";
//Initializes window, buttons, panels, textfield and other variables
JFrame window = new JFrame("Calculator " + VERSION);
JMenuBar Menu = new JMenuBar();
JMenu mnuProgram, mnuView, mnuHelp;
JMenuItem mnuReset, mnuExit, mnuAbout;
JCheckBoxMenuItem mnuShowCalc;
JPanel pnlBottom, pnlBackspace, pnlClear, pnlButtons, pnlCalculation;
JLabel lblFirst, lblOperator, lblSecond, lblEqual, lblResult;
JTextField txtDisplay;
JButton buttons[] = new JButton[23];
final short MAX_INPUT = 30;
final float DIVIDE_ZERO_ERROR = (float)-.04060802;
final float ERROR = (float)-.04060801;
String tempNum;
String sign;
String Label;
String R;
String tempString;
double number1, number2, result;
boolean decimalUsed, secondNum, makeSecondTrue, lblSecondNum, secondEqual, error;
//constructor for Calculator class
Calculator() {
//Window Properties
window.setSize(306, 210);
window.setLocation(470, 290);
window.setLayout(new BorderLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
//Making the Menu and Menu Items and adding action listener/item listener
mnuProgram = new JMenu("Program");
mnuView = new JMenu("View");
mnuHelp = new JMenu("Help");
Menu.add(mnuProgram);
Menu.add(mnuView);
Menu.add(mnuHelp);
mnuReset = new JMenuItem("Reset");
mnuExit = new JMenuItem("Exit");
mnuShowCalc = new JCheckBoxMenuItem("Show Calculations");
mnuAbout = new JMenuItem("About Calculator");
mnuProgram.add(mnuReset);
mnuProgram.add(mnuExit);
mnuView.add(mnuShowCalc);
mnuHelp.add(mnuAbout);
mnuReset.addActionListener(this);
mnuExit.addActionListener(this);
mnuShowCalc.addItemListener(this);
mnuAbout.addActionListener(this);
//Making Panels
/* pnlButtons holds all the Buttons Except for Backspace, CE, and C buttons
pnlClear holds CE and C Buttons
pnlBackspace holds the Backspace Button
pnlBottom holds all the other Panels so I can put them all at the bottom of the window
pnlCalculations holds all the Labels for the Show Calcualtions function */
pnlBottom = new JPanel();
pnlBackspace = new JPanel();
pnlClear = new JPanel();
pnlButtons = new JPanel();
pnlCalculation = new JPanel();
//Setting Layouts for the Panels and other Properties
pnlBottom.setLayout(new BorderLayout());
pnlButtons.setLayout(new GridLayout(4, 5, 2, 2));
pnlClear.setLayout(new GridLayout(1, 2, 2, 2));
pnlBackspace.setLayout(new GridLayout(1, 2, 2, 2));
pnlCalculation.setLayout(new FlowLayout(FlowLayout.CENTER));
pnlBottom.setBackground(new Color(200, 200, 200));
//Making Labels and adding them to pnlCalculation Panel.
lblFirst = new JLabel();
lblOperator = new JLabel();
lblSecond = new JLabel();
lblEqual = new JLabel();
lblResult = new JLabel();
pnlCalculation.add(lblFirst);
pnlCalculation.add(lblOperator);
pnlCalculation.add(lblSecond);
pnlCalculation.add(lblEqual);
pnlCalculation.add(lblResult);
//Text Field Properties
txtDisplay = new JTextField("0");
txtDisplay.setEditable(false);
txtDisplay.setHorizontalAlignment(JTextField.TRAILING);
txtDisplay.setBackground(Color.WHITE);
txtDisplay.setOpaque(true);
txtDisplay.addKeyListener(this);
//Making Buttons and adding to Panel Buttons
buttons[0] = new JButton("0");
buttons[10] = new JButton(".");
buttons[11] = new JButton("=");
buttons[12] = new JButton("/");
buttons[13] = new JButton("*");
buttons[14] = new JButton("-");
buttons[15] = new JButton("+");
buttons[16] = new JButton("sqrt");
buttons[17] = new JButton("%");
buttons[18] = new JButton("1/x");
buttons[19] = new JButton("+/-");
for(int i=7; i<10; i++) {
buttons[i] = new JButton(String.valueOf(i));
pnlButtons.add(buttons[i]);
}
pnlButtons.add(buttons[12]);
pnlButtons.add(buttons[16]);
for(int i=4; i<7; i++) {
buttons[i] = new JButton(String.valueOf(i));
pnlButtons.add(buttons[i]);
}
pnlButtons.add(buttons[13]);
pnlButtons.add(buttons[17]);
for(int i=1; i<4; i++) {
buttons[i] = new JButton(String.valueOf(i));
pnlButtons.add(buttons[i]);
}
pnlButtons.add(buttons[14]);
pnlButtons.add(buttons[18]);
pnlButtons.add(buttons[0]);
pnlButtons.add(buttons[10]);
pnlButtons.add(buttons[11]);
pnlButtons.add(buttons[15]);
pnlButtons.add(buttons[19]);
//Creating Backspace Button and adding it to Backspace panel
buttons[20] = new JButton("BackSpace");
pnlBackspace.add(buttons[20]);
//Creating Clear Buttons and adding it to Clear panel
buttons[21] = new JButton("CE");
buttons[22] = new JButton(" C ");
pnlClear.add(buttons[21]);
pnlClear.add(buttons[22]);
/*Adds Action Listener to every button
and adds color to all the numbered buttons
plus the decimal and all the other buttons
to red */
for(int i=0; i<buttons.length; i++) {
buttons[i].addActionListener(this);
if(i<11 || (i>15 && i<20))
buttons[i].setForeground(Color.blue);
else
buttons[i].setForeground(Color.red);
}
//Adds Panels to window and shows window
pnlBottom.add(txtDisplay, BorderLayout.NORTH);
pnlBottom.add(pnlBackspace, BorderLayout.WEST);
pnlBottom.add(pnlClear, BorderLayout.EAST);
pnlBottom.add(pnlButtons, BorderLayout.SOUTH);
window.add(Menu, BorderLayout.NORTH);
window.add(pnlCalculation);
window.add(pnlBottom, BorderLayout.SOUTH);
window.setVisible(true);
pnlCalculation.setVisible(false);
//Clears the screen. sets Variables to default.
Clear();
}
public void actionPerformed(ActionEvent click) {
// Adding Digits to Screen
for(int i=0; i<10; i++) {
if(click.getSource() == buttons[i])
addDigit(String.valueOf(i));
}
// Adding Decimal Point to Screen
if(click.getSource() == buttons[10]) {
if(!decimalUsed) {
addDigit(".");
decimalUsed = true;
}
}
for(int i=11; i<buttons.length; i++) {
if(click.getSource() == buttons[i]) {
switch(i) {
case 11:
Calculate("=");// EQUAL
break;
case 12:
Calculate("/");// DIVDIE
break;
case 13:
Calculate("*");// MULTIPLY
break;
case 14:
Calculate("-");// SUBTRACT
break;
case 15:
Calculate("+");// ADD
break;
case 16:// SQUARE ROOT
sqrt();
break;
case 17:// %
percent();
break;
case 18:// 1/x
divideByX();
break;
case 19:// +/-
signChange();
break;
case 20:// BACKSPACE
Backspace();
break;
case 21:// CE
ClearExisting();
break;
case 22:// C
Clear();
break;
}
}
}
if(!(buttons[11] == click.getSource()))
secondEqual = false;
// Program -> Reset
if(click.getSource() == mnuReset) {
Clear();
window.setSize(306, 210);
pnlCalculation.setVisible(false);
mnuShowCalc.setState(false);
JOptionPane.showMessageDialog(null, "Reset!\nEverthing is back to default."
, "Reset", JOptionPane.INFORMATION_MESSAGE);
}
// Program -> Exit
if(click.getSource() == mnuExit) {
System.exit(0);
}
// Help -> About
if(click.getSource() == mnuAbout) {
showAboutDialog();
}
txtDisplay.requestFocus();
}
/* If the Menu Checkbox is clicked it will make the pnlCalculation visible and the window
bigger so the user can see it too. if it is unseleceted it will go back to normal */
public void itemStateChanged(ItemEvent click) {
if(click.getSource() == mnuShowCalc) {
if(click.getStateChange() == ItemEvent.SELECTED) {
window.setSize(306, 235);
pnlCalculation.setVisible(true);
} else {
window.setSize(306, 210);
pnlCalculation.setVisible(false);
}
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyChar();
if(!(key == KeyEvent.VK_ENTER))
secondEqual = false;
switch(key) {
case KeyEvent.VK_0:
addDigit("0");
break;
case KeyEvent.VK_1:
addDigit("1");
break;
case KeyEvent.VK_2:
addDigit("2");
break;
case KeyEvent.VK_3:
addDigit("3");
break;
case KeyEvent.VK_4:
addDigit("4");
break;
case KeyEvent.VK_5:
addDigit("5");
break;
case KeyEvent.VK_6:
addDigit("6");
break;
case KeyEvent.VK_7:
addDigit("7");
break;
case KeyEvent.VK_8:
addDigit("8");
break;
case KeyEvent.VK_9:
addDigit("9");
break;
case KeyEvent.VK_PERIOD:
if(!decimalUsed) {
addDigit(".");
decimalUsed = true;
}
break;
case KeyEvent.VK_ENTER:
Calculate("=");
break;
case KeyEvent.VK_SLASH:
Calculate("/");
break;
case 42:
Calculate("*");
break;
case KeyEvent.VK_MINUS:
Calculate("-");
break;
case 43:
Calculate("+");
break;
case KeyEvent.VK_BACK_SPACE:
Backspace();
break;
case KeyEvent.VK_ESCAPE:
Clear();
break;
case KeyEvent.VK_DELETE:
ClearExisting();
break;
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
/*********************************************************************************************************************************
NON-LISTENER METHODS
/*********************************************************************************************************************************/
/* adds Digit to screen
But if TempNum is empty and the button we click is 0 then just set the display box to 0 */
public void addDigit(String digit) {
if(!error) {
if(tempNum.equals("") && digit.equals("0")) {
txtDisplay.setText("0");
tempNum = "";
if(lblSecondNum)
lblSecond.setText("0");
else {
lblFirst.setText("0");
lblSecond.setText("_");
lblResult.setText("_");
}
} else if(tempNum.length() < MAX_INPUT) {
tempNum += digit;
if(tempNum.charAt(0) == '.')
tempNum = "0" + tempNum;
txtDisplay.setText(tempNum);
if(makeSecondTrue)
secondNum = true;
checkLabels();
}
secondEqual = false;
}
}
/* Calculates if /, *, -, +, or = sign is pressed
Second and makeSecondTrue are here because
Second should only be true if a digit is pressed after the First Part */
public void Calculate(String operator) {
if(!error) {
decimalUsed = false;
if(operator.equals("=")) {
if(secondEqual) { ///////////
number1 = result; //
result = Process(); //Equal Sign Pressed Twice or more
Display(result); //
} else { /////////// ////////////////////
number2 = Double.parseDouble(txtDisplay.getText()); //
setSecondLabel(); //
result = Process(); //Equal Sign Pressed Once
Display(result); //
number1 = result; //
secondEqual = true; //
} ////////////////////
secondNum = false;
makeSecondTrue = false;
lblSecondNum = false;
} else {
if(secondNum) { /////////////////
number2 = Double.parseDouble(txtDisplay.getText());
setSecondLabel(); //
result = Process(); //
Display(result); //Second Part
number1 = result; //
lblSecond.setText("_"); //
lblResult.setText("_"); //
lblOperator.setText("?"); //
setFirstLabel(String.valueOf(result));
secondNum = false; //
} else { ///////////////// ///////////////////
number1 = Double.parseDouble(txtDisplay.getText()); //
makeSecondTrue = true; //
setFirstLabel(); //
lblSecond.setText("_"); //First Part
lblResult.setText("_"); //
lblOperator.setText("?"); //
lblSecondNum = true; //
} ////////////////////
sign = operator;
secondEqual = false;
}
lblOperator.setText(sign);
tempNum = "";
}
}
/* Makes the number in text field SecondNum
Returns the result of whatever calculation the user has pressed ( / , * , - , + ) */
public double Process() {
if(sign.equals("*"))
return (number1 * number2);
else if(sign.equals("-"))
return (number1 - number2);
else if(sign.equals("+"))
return (number1 + number2);
else if(sign.equals("/")) {
if(number2 == 0)
return DIVIDE_ZERO_ERROR; //if second number is 0 and it is a division operator, return DIVIDE_ZERO_ERROR
// so when displayed, it gives a message, "Cannot Divide by Zero"
else
return (number1 / number2);
}
else
return ERROR; //anything other than (/, *, -, +) should return ERROR so when displayed it gives error
}
//Displays a double number unless if some errors are created
public void Display(double num) {
if(num == DIVIDE_ZERO_ERROR) {
R = "Cannot Divide by Zero!";
error = true;
}
else if(num == ERROR) {
R = "Invalid Input for Function!";
error = true;
}
else {
R = String.valueOf(num);
if((R.charAt((R.length()) -1) == '0') && (R.charAt((R.length()) -2) == '.'))
R = R.substring(0, R.length() - 2);
}
txtDisplay.setText(R);
lblResult.setText(R);
setFirstLabel();
}
//Square Root function. (sqrt)
public void sqrt() {
if(!error) {
tempString = txtDisplay.getText();
try {result = Math.sqrt(Double.parseDouble(tempString));} catch(Exception e) {result = ERROR;}
if(tempString.indexOf("-") == 0)
result = ERROR;
lblSecond.setText("sqrt( " + tempString + " )");
Display(result);
lblFirst.setText("");
lblOperator.setText("");
secondNum = false;
makeSecondTrue = false;
lblSecondNum = false;
tempNum = "";
}
}
//converts number to percent (%)
public void percent() {
if(!error) {
tempString = txtDisplay.getText();
try {result = (Double.parseDouble(tempString) / 100);} catch(Exception e) {result = ERROR;}
Display(result);
setFirstLabel(tempString);
lblOperator.setText("/");
setSecondLabel("100");
secondNum = false;
makeSecondTrue = false;
lblSecondNum = false;
tempNum = "";
}
}
//1 Divide by X function (1/x)
public void divideByX() {
if(!error) {
tempString = txtDisplay.getText();
if(tempString.equals("0"))
result = DIVIDE_ZERO_ERROR;
else
try {result = 1 / Double.parseDouble(tempString);} catch(Exception e) {result = ERROR;}
setSecondLabel(tempString);
Display(result);
setFirstLabel("1");
lblOperator.setText("/");
secondNum = false;
makeSecondTrue = false;
lblSecondNum = false;
tempNum = "";
}
}
//Makes it negative if positive and vice versa
public void signChange() {
if(!error) {
tempString = txtDisplay.getText();
if(tempString.equals("0"))
{
/* Do Nothing*/
} else {
if(tempString.charAt(0) == '-')
tempNum = tempNum.substring(1, tempNum.length());
else
tempNum = "-" + tempString;
txtDisplay.setText(tempNum);
checkLabels();
}
}
}
/* Checks the labels in pnlCalulation to the correct number corresponding with
whatever user types in. */
public void checkLabels() {
if(tempNum.equals("")) {
if(lblSecondNum) {
setFirstLabel();
lblSecond.setText("_"); }
else {
lblFirst.setText("_");
lblSecond.setText("_");
lblResult.setText("_");
lblOperator.setText("?");
}
} else {
if(lblSecondNum)
lblSecond.setText(tempNum);
else {
lblFirst.setText(tempNum);
lblSecond.setText("_");
lblResult.setText("_");
lblOperator.setText("?");
}
}
}
/* First Number Label, lblFirst, gets set the number1 without the .0 at the end.
Sets lblFirst to whatever number1 is depending on where it is needed. */
public void setFirstLabel() {
Label = String.valueOf(number1);
if(Label.length() > 2) {
if(Label.charAt(Label.length() - 1) == '0' && Label.charAt(Label.length() - 2) == '.')
Label = Label.substring(0, Label.length() - 2);
}
lblFirst.setText(Label);
}
public void setFirstLabel(String f) {
if(f.length() > 2) {
if(f.charAt(f.length() - 1) == '0' && f.charAt(f.length() - 2) == '.')
f = f.substring(0, f.length() - 2);
}
lblFirst.setText(f);
}
public void setSecondLabel() {
Label = String.valueOf(number2);
lblResult.setText("_");
if(Label.length() > 2) {
if(Label.charAt(Label.length() - 1) == '0' && Label.charAt(Label.length() - 2) == '.')
Label = Label.substring(0, Label.length() - 2);
}
lblSecond.setText(Label);
}
public void setSecondLabel(String s) {
if(s.length() > 2) {
if(s.charAt(s.length() - 1) == '0' && s.charAt(s.length() - 2) == '.')
s = s.substring(0, s.length() - 2);
}
lblSecond.setText(s);
}
//Backspace
public void Backspace() {
if(!error) {
if(txtDisplay.getText().length() < 2) {
tempNum = "";
txtDisplay.setText("0");
} else {
if((txtDisplay.getText().charAt(txtDisplay.getText().length() - 1) == '.' &&
txtDisplay.getText().charAt(txtDisplay.getText().length() - 2) == '0') ||
(txtDisplay.getText().length() == 2 && txtDisplay.getText().charAt(0) == '-')) {
tempNum = "";
txtDisplay.setText("0");
decimalUsed = false;
} else {
if(txtDisplay.getText().charAt(txtDisplay.getText().length() - 1) == '.')
decimalUsed = false;
tempNum = txtDisplay.getText().substring(0, txtDisplay.getText().length() - 1);
txtDisplay.setText(tempNum);
}
}
checkLabels();
}
}
//Clears First Number or Second Number or everything if result has been shown.
public void ClearExisting() {
tempNum = "";
txtDisplay.setText("0");
decimalUsed = false;
checkLabels();
error = false;
}
//Resets everything to startup
public void Clear() {
tempNum = ""; sign = "0"; tempString = "";
Label = ""; R = "";
txtDisplay.setText("0");
lblFirst.setText("_");
lblOperator.setText("?");
lblSecond.setText("_");
lblEqual.setText("=");
lblResult.setText("_");
number1 = 0.0; number2 = 0.0; result = 0.0;
decimalUsed = false; secondNum = false; makeSecondTrue = false;
lblSecondNum = false; secondEqual = false; error = false;
}
//Shows the About Calculator Dialog
public void showAboutDialog() {
/* JDialog(Frame, Title, boolean)
boolean: for if you want the dialog to be a pop-up so you
have to do something to make it go away or another kind of frame
beside your original frame. */
JDialog dlgAbout = new JDialog(window, "About Calculator", true);
JTextArea txtAbout = new JTextArea(4, 4);
txtAbout.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel pnlAbout = new JPanel(new FlowLayout(FlowLayout.CENTER));
String about;
about = "Calculator" + "\n\n" +
"Version: " + VERSION + "\n" +
"Created: August 7, 2008" + "\n" +
"Author: Blmaster";
txtAbout.setText(about);
txtAbout.setEditable(false);
txtAbout.setBackground(new Color(240, 240, 240));
pnlAbout.add(txtAbout);
pnlAbout.setBackground(Color.blue);
dlgAbout.add(pnlAbout);
dlgAbout.setSize(180, 122);
dlgAbout.setLocation(window.getX() + 60, window.getY() + 50);
dlgAbout.setResizable(false);
dlgAbout.setVisible(true);
}
/* Since you cant call a class (you can only call a method),
we have to make a instance of it. An example would be like,
you cant call a car so it magically appears in front of you,
but you can make a car. Something like that.
The "new" makes a new Calculator and pretty much calls
the code in the class contructor. */
public static void main(String[] args) {
new Calculator();
}
}
/*
Version Changes:
0.5- made basic layout of application.
1.0- added basic (/, *, -, +) operator functions.
1.1- added function: lets you keep calculating without hitting "=" button.
1.15- fixed bug: wouldnt work after first time.
1.2- added function: Clear button.
1.3- added function: Clear Exisiting button.
1.4- reorganized code: works more efficient now.
1.6- added function: change operator sign.
1.65- fixed bug: intefered with equal sign.
1.7- added function: MAX_INPUT for textbox
1.75- fixed bug: after textbox has reached MAX_INPUT, wouldnt work.
1.8- added function: Backspace button.
1.85- fixed (1.6) bug: 1.6 function wouldnt work after first use.
2.0- improved: error system, reorganized code, C, CE, Backspace Buttons.
2.1- added function: menu bar. Program --> Reset, Exit
2.2- added Help --> About to menu bar.
2.5- added View --> Show Calculations to menu bar. (beta)
2/6- replaced About with a Dialog Message.
2.7- fixed Show Calculations. (a lot of work)
2.8- reorganized code: show calculation function is cleaned to work more efficiently.
2.9- fixed bug: 0 button would add 0 in front of number. Ex. 032
2.95- fixed (1.8) bug: Backspace wouldnt make decimal work if it erases decimal.
2.99- fixed (2.5) bugs: another Show Calculation bug. wouldnt show 0.
3.0- Menu Bar, Show Calculation function, removed all the ".0" at end of number. STABLE
3.2- added (sqrt, %, 1/x, +/-) functions.
3.25- fixed bugs: 3.2 functions intefered with labels.
3.4- reorganized code: more methods for easier understanding.
3.5- added Key Listener: Numper Pad in keyboard works with Calculator.
3.55- fixed (3.2) bugs: you can start over after doing functions.
3.59- fixed bug: first number label always showing 0 with percent button.
3.6- fixed bug: sqrt function would display error as number.
3.65- fixed bug: the equal button would calculate wrongly when pressed twice in a row.
3.7- added function: forces user to clear or clear exisiting or reset to get out of error.
3.8- changed About dialog.
4.0- FINISHED
*/
Title: Calculator App
Created: August 7, 2008
Author: Blmaster
Comments:
Wanted to see if I could make it.
Last Edited: August 20, 2008
Changes:
See Bottom of Code ||
*******************\/
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator implements ActionListener, ItemListener, KeyListener {
private final String VERSION = "4.0";
//Initializes window, buttons, panels, textfield and other variables
JFrame window = new JFrame("Calculator " + VERSION);
JMenuBar Menu = new JMenuBar();
JMenu mnuProgram, mnuView, mnuHelp;
JMenuItem mnuReset, mnuExit, mnuAbout;
JCheckBoxMenuItem mnuShowCalc;
JPanel pnlBottom, pnlBackspace, pnlClear, pnlButtons, pnlCalculation;
JLabel lblFirst, lblOperator, lblSecond, lblEqual, lblResult;
JTextField txtDisplay;
JButton buttons[] = new JButton[23];
final short MAX_INPUT = 30;
final float DIVIDE_ZERO_ERROR = (float)-.04060802;
final float ERROR = (float)-.04060801;
String tempNum;
String sign;
String Label;
String R;
String tempString;
double number1, number2, result;
boolean decimalUsed, secondNum, makeSecondTrue, lblSecondNum, secondEqual, error;
//constructor for Calculator class
Calculator() {
//Window Properties
window.setSize(306, 210);
window.setLocation(470, 290);
window.setLayout(new BorderLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
//Making the Menu and Menu Items and adding action listener/item listener
mnuProgram = new JMenu("Program");
mnuView = new JMenu("View");
mnuHelp = new JMenu("Help");
Menu.add(mnuProgram);
Menu.add(mnuView);
Menu.add(mnuHelp);
mnuReset = new JMenuItem("Reset");
mnuExit = new JMenuItem("Exit");
mnuShowCalc = new JCheckBoxMenuItem("Show Calculations");
mnuAbout = new JMenuItem("About Calculator");
mnuProgram.add(mnuReset);
mnuProgram.add(mnuExit);
mnuView.add(mnuShowCalc);
mnuHelp.add(mnuAbout);
mnuReset.addActionListener(this);
mnuExit.addActionListener(this);
mnuShowCalc.addItemListener(this);
mnuAbout.addActionListener(this);
//Making Panels
/* pnlButtons holds all the Buttons Except for Backspace, CE, and C buttons
pnlClear holds CE and C Buttons
pnlBackspace holds the Backspace Button
pnlBottom holds all the other Panels so I can put them all at the bottom of the window
pnlCalculations holds all the Labels for the Show Calcualtions function */
pnlBottom = new JPanel();
pnlBackspace = new JPanel();
pnlClear = new JPanel();
pnlButtons = new JPanel();
pnlCalculation = new JPanel();
//Setting Layouts for the Panels and other Properties
pnlBottom.setLayout(new BorderLayout());
pnlButtons.setLayout(new GridLayout(4, 5, 2, 2));
pnlClear.setLayout(new GridLayout(1, 2, 2, 2));
pnlBackspace.setLayout(new GridLayout(1, 2, 2, 2));
pnlCalculation.setLayout(new FlowLayout(FlowLayout.CENTER));
pnlBottom.setBackground(new Color(200, 200, 200));
//Making Labels and adding them to pnlCalculation Panel.
lblFirst = new JLabel();
lblOperator = new JLabel();
lblSecond = new JLabel();
lblEqual = new JLabel();
lblResult = new JLabel();
pnlCalculation.add(lblFirst);
pnlCalculation.add(lblOperator);
pnlCalculation.add(lblSecond);
pnlCalculation.add(lblEqual);
pnlCalculation.add(lblResult);
//Text Field Properties
txtDisplay = new JTextField("0");
txtDisplay.setEditable(false);
txtDisplay.setHorizontalAlignment(JTextField.TRAILING);
txtDisplay.setBackground(Color.WHITE);
txtDisplay.setOpaque(true);
txtDisplay.addKeyListener(this);
//Making Buttons and adding to Panel Buttons
buttons[0] = new JButton("0");
buttons[10] = new JButton(".");
buttons[11] = new JButton("=");
buttons[12] = new JButton("/");
buttons[13] = new JButton("*");
buttons[14] = new JButton("-");
buttons[15] = new JButton("+");
buttons[16] = new JButton("sqrt");
buttons[17] = new JButton("%");
buttons[18] = new JButton("1/x");
buttons[19] = new JButton("+/-");
for(int i=7; i<10; i++) {
buttons[i] = new JButton(String.valueOf(i));
pnlButtons.add(buttons[i]);
}
pnlButtons.add(buttons[12]);
pnlButtons.add(buttons[16]);
for(int i=4; i<7; i++) {
buttons[i] = new JButton(String.valueOf(i));
pnlButtons.add(buttons[i]);
}
pnlButtons.add(buttons[13]);
pnlButtons.add(buttons[17]);
for(int i=1; i<4; i++) {
buttons[i] = new JButton(String.valueOf(i));
pnlButtons.add(buttons[i]);
}
pnlButtons.add(buttons[14]);
pnlButtons.add(buttons[18]);
pnlButtons.add(buttons[0]);
pnlButtons.add(buttons[10]);
pnlButtons.add(buttons[11]);
pnlButtons.add(buttons[15]);
pnlButtons.add(buttons[19]);
//Creating Backspace Button and adding it to Backspace panel
buttons[20] = new JButton("BackSpace");
pnlBackspace.add(buttons[20]);
//Creating Clear Buttons and adding it to Clear panel
buttons[21] = new JButton("CE");
buttons[22] = new JButton(" C ");
pnlClear.add(buttons[21]);
pnlClear.add(buttons[22]);
/*Adds Action Listener to every button
and adds color to all the numbered buttons
plus the decimal and all the other buttons
to red */
for(int i=0; i<buttons.length; i++) {
buttons[i].addActionListener(this);
if(i<11 || (i>15 && i<20))
buttons[i].setForeground(Color.blue);
else
buttons[i].setForeground(Color.red);
}
//Adds Panels to window and shows window
pnlBottom.add(txtDisplay, BorderLayout.NORTH);
pnlBottom.add(pnlBackspace, BorderLayout.WEST);
pnlBottom.add(pnlClear, BorderLayout.EAST);
pnlBottom.add(pnlButtons, BorderLayout.SOUTH);
window.add(Menu, BorderLayout.NORTH);
window.add(pnlCalculation);
window.add(pnlBottom, BorderLayout.SOUTH);
window.setVisible(true);
pnlCalculation.setVisible(false);
//Clears the screen. sets Variables to default.
Clear();
}
public void actionPerformed(ActionEvent click) {
// Adding Digits to Screen
for(int i=0; i<10; i++) {
if(click.getSource() == buttons[i])
addDigit(String.valueOf(i));
}
// Adding Decimal Point to Screen
if(click.getSource() == buttons[10]) {
if(!decimalUsed) {
addDigit(".");
decimalUsed = true;
}
}
for(int i=11; i<buttons.length; i++) {
if(click.getSource() == buttons[i]) {
switch(i) {
case 11:
Calculate("=");// EQUAL
break;
case 12:
Calculate("/");// DIVDIE
break;
case 13:
Calculate("*");// MULTIPLY
break;
case 14:
Calculate("-");// SUBTRACT
break;
case 15:
Calculate("+");// ADD
break;
case 16:// SQUARE ROOT
sqrt();
break;
case 17:// %
percent();
break;
case 18:// 1/x
divideByX();
break;
case 19:// +/-
signChange();
break;
case 20:// BACKSPACE
Backspace();
break;
case 21:// CE
ClearExisting();
break;
case 22:// C
Clear();
break;
}
}
}
if(!(buttons[11] == click.getSource()))
secondEqual = false;
// Program -> Reset
if(click.getSource() == mnuReset) {
Clear();
window.setSize(306, 210);
pnlCalculation.setVisible(false);
mnuShowCalc.setState(false);
JOptionPane.showMessageDialog(null, "Reset!\nEverthing is back to default."
, "Reset", JOptionPane.INFORMATION_MESSAGE);
}
// Program -> Exit
if(click.getSource() == mnuExit) {
System.exit(0);
}
// Help -> About
if(click.getSource() == mnuAbout) {
showAboutDialog();
}
txtDisplay.requestFocus();
}
/* If the Menu Checkbox is clicked it will make the pnlCalculation visible and the window
bigger so the user can see it too. if it is unseleceted it will go back to normal */
public void itemStateChanged(ItemEvent click) {
if(click.getSource() == mnuShowCalc) {
if(click.getStateChange() == ItemEvent.SELECTED) {
window.setSize(306, 235);
pnlCalculation.setVisible(true);
} else {
window.setSize(306, 210);
pnlCalculation.setVisible(false);
}
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyChar();
if(!(key == KeyEvent.VK_ENTER))
secondEqual = false;
switch(key) {
case KeyEvent.VK_0:
addDigit("0");
break;
case KeyEvent.VK_1:
addDigit("1");
break;
case KeyEvent.VK_2:
addDigit("2");
break;
case KeyEvent.VK_3:
addDigit("3");
break;
case KeyEvent.VK_4:
addDigit("4");
break;
case KeyEvent.VK_5:
addDigit("5");
break;
case KeyEvent.VK_6:
addDigit("6");
break;
case KeyEvent.VK_7:
addDigit("7");
break;
case KeyEvent.VK_8:
addDigit("8");
break;
case KeyEvent.VK_9:
addDigit("9");
break;
case KeyEvent.VK_PERIOD:
if(!decimalUsed) {
addDigit(".");
decimalUsed = true;
}
break;
case KeyEvent.VK_ENTER:
Calculate("=");
break;
case KeyEvent.VK_SLASH:
Calculate("/");
break;
case 42:
Calculate("*");
break;
case KeyEvent.VK_MINUS:
Calculate("-");
break;
case 43:
Calculate("+");
break;
case KeyEvent.VK_BACK_SPACE:
Backspace();
break;
case KeyEvent.VK_ESCAPE:
Clear();
break;
case KeyEvent.VK_DELETE:
ClearExisting();
break;
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
/*********************************************************************************************************************************
NON-LISTENER METHODS
/*********************************************************************************************************************************/
/* adds Digit to screen
But if TempNum is empty and the button we click is 0 then just set the display box to 0 */
public void addDigit(String digit) {
if(!error) {
if(tempNum.equals("") && digit.equals("0")) {
txtDisplay.setText("0");
tempNum = "";
if(lblSecondNum)
lblSecond.setText("0");
else {
lblFirst.setText("0");
lblSecond.setText("_");
lblResult.setText("_");
}
} else if(tempNum.length() < MAX_INPUT) {
tempNum += digit;
if(tempNum.charAt(0) == '.')
tempNum = "0" + tempNum;
txtDisplay.setText(tempNum);
if(makeSecondTrue)
secondNum = true;
checkLabels();
}
secondEqual = false;
}
}
/* Calculates if /, *, -, +, or = sign is pressed
Second and makeSecondTrue are here because
Second should only be true if a digit is pressed after the First Part */
public void Calculate(String operator) {
if(!error) {
decimalUsed = false;
if(operator.equals("=")) {
if(secondEqual) { ///////////
number1 = result; //
result = Process(); //Equal Sign Pressed Twice or more
Display(result); //
} else { /////////// ////////////////////
number2 = Double.parseDouble(txtDisplay.getText()); //
setSecondLabel(); //
result = Process(); //Equal Sign Pressed Once
Display(result); //
number1 = result; //
secondEqual = true; //
} ////////////////////
secondNum = false;
makeSecondTrue = false;
lblSecondNum = false;
} else {
if(secondNum) { /////////////////
number2 = Double.parseDouble(txtDisplay.getText());
setSecondLabel(); //
result = Process(); //
Display(result); //Second Part
number1 = result; //
lblSecond.setText("_"); //
lblResult.setText("_"); //
lblOperator.setText("?"); //
setFirstLabel(String.valueOf(result));
secondNum = false; //
} else { ///////////////// ///////////////////
number1 = Double.parseDouble(txtDisplay.getText()); //
makeSecondTrue = true; //
setFirstLabel(); //
lblSecond.setText("_"); //First Part
lblResult.setText("_"); //
lblOperator.setText("?"); //
lblSecondNum = true; //
} ////////////////////
sign = operator;
secondEqual = false;
}
lblOperator.setText(sign);
tempNum = "";
}
}
/* Makes the number in text field SecondNum
Returns the result of whatever calculation the user has pressed ( / , * , - , + ) */
public double Process() {
if(sign.equals("*"))
return (number1 * number2);
else if(sign.equals("-"))
return (number1 - number2);
else if(sign.equals("+"))
return (number1 + number2);
else if(sign.equals("/")) {
if(number2 == 0)
return DIVIDE_ZERO_ERROR; //if second number is 0 and it is a division operator, return DIVIDE_ZERO_ERROR
// so when displayed, it gives a message, "Cannot Divide by Zero"
else
return (number1 / number2);
}
else
return ERROR; //anything other than (/, *, -, +) should return ERROR so when displayed it gives error
}
//Displays a double number unless if some errors are created
public void Display(double num) {
if(num == DIVIDE_ZERO_ERROR) {
R = "Cannot Divide by Zero!";
error = true;
}
else if(num == ERROR) {
R = "Invalid Input for Function!";
error = true;
}
else {
R = String.valueOf(num);
if((R.charAt((R.length()) -1) == '0') && (R.charAt((R.length()) -2) == '.'))
R = R.substring(0, R.length() - 2);
}
txtDisplay.setText(R);
lblResult.setText(R);
setFirstLabel();
}
//Square Root function. (sqrt)
public void sqrt() {
if(!error) {
tempString = txtDisplay.getText();
try {result = Math.sqrt(Double.parseDouble(tempString));} catch(Exception e) {result = ERROR;}
if(tempString.indexOf("-") == 0)
result = ERROR;
lblSecond.setText("sqrt( " + tempString + " )");
Display(result);
lblFirst.setText("");
lblOperator.setText("");
secondNum = false;
makeSecondTrue = false;
lblSecondNum = false;
tempNum = "";
}
}
//converts number to percent (%)
public void percent() {
if(!error) {
tempString = txtDisplay.getText();
try {result = (Double.parseDouble(tempString) / 100);} catch(Exception e) {result = ERROR;}
Display(result);
setFirstLabel(tempString);
lblOperator.setText("/");
setSecondLabel("100");
secondNum = false;
makeSecondTrue = false;
lblSecondNum = false;
tempNum = "";
}
}
//1 Divide by X function (1/x)
public void divideByX() {
if(!error) {
tempString = txtDisplay.getText();
if(tempString.equals("0"))
result = DIVIDE_ZERO_ERROR;
else
try {result = 1 / Double.parseDouble(tempString);} catch(Exception e) {result = ERROR;}
setSecondLabel(tempString);
Display(result);
setFirstLabel("1");
lblOperator.setText("/");
secondNum = false;
makeSecondTrue = false;
lblSecondNum = false;
tempNum = "";
}
}
//Makes it negative if positive and vice versa
public void signChange() {
if(!error) {
tempString = txtDisplay.getText();
if(tempString.equals("0"))
{
/* Do Nothing*/
} else {
if(tempString.charAt(0) == '-')
tempNum = tempNum.substring(1, tempNum.length());
else
tempNum = "-" + tempString;
txtDisplay.setText(tempNum);
checkLabels();
}
}
}
/* Checks the labels in pnlCalulation to the correct number corresponding with
whatever user types in. */
public void checkLabels() {
if(tempNum.equals("")) {
if(lblSecondNum) {
setFirstLabel();
lblSecond.setText("_"); }
else {
lblFirst.setText("_");
lblSecond.setText("_");
lblResult.setText("_");
lblOperator.setText("?");
}
} else {
if(lblSecondNum)
lblSecond.setText(tempNum);
else {
lblFirst.setText(tempNum);
lblSecond.setText("_");
lblResult.setText("_");
lblOperator.setText("?");
}
}
}
/* First Number Label, lblFirst, gets set the number1 without the .0 at the end.
Sets lblFirst to whatever number1 is depending on where it is needed. */
public void setFirstLabel() {
Label = String.valueOf(number1);
if(Label.length() > 2) {
if(Label.charAt(Label.length() - 1) == '0' && Label.charAt(Label.length() - 2) == '.')
Label = Label.substring(0, Label.length() - 2);
}
lblFirst.setText(Label);
}
public void setFirstLabel(String f) {
if(f.length() > 2) {
if(f.charAt(f.length() - 1) == '0' && f.charAt(f.length() - 2) == '.')
f = f.substring(0, f.length() - 2);
}
lblFirst.setText(f);
}
public void setSecondLabel() {
Label = String.valueOf(number2);
lblResult.setText("_");
if(Label.length() > 2) {
if(Label.charAt(Label.length() - 1) == '0' && Label.charAt(Label.length() - 2) == '.')
Label = Label.substring(0, Label.length() - 2);
}
lblSecond.setText(Label);
}
public void setSecondLabel(String s) {
if(s.length() > 2) {
if(s.charAt(s.length() - 1) == '0' && s.charAt(s.length() - 2) == '.')
s = s.substring(0, s.length() - 2);
}
lblSecond.setText(s);
}
//Backspace
public void Backspace() {
if(!error) {
if(txtDisplay.getText().length() < 2) {
tempNum = "";
txtDisplay.setText("0");
} else {
if((txtDisplay.getText().charAt(txtDisplay.getText().length() - 1) == '.' &&
txtDisplay.getText().charAt(txtDisplay.getText().length() - 2) == '0') ||
(txtDisplay.getText().length() == 2 && txtDisplay.getText().charAt(0) == '-')) {
tempNum = "";
txtDisplay.setText("0");
decimalUsed = false;
} else {
if(txtDisplay.getText().charAt(txtDisplay.getText().length() - 1) == '.')
decimalUsed = false;
tempNum = txtDisplay.getText().substring(0, txtDisplay.getText().length() - 1);
txtDisplay.setText(tempNum);
}
}
checkLabels();
}
}
//Clears First Number or Second Number or everything if result has been shown.
public void ClearExisting() {
tempNum = "";
txtDisplay.setText("0");
decimalUsed = false;
checkLabels();
error = false;
}
//Resets everything to startup
public void Clear() {
tempNum = ""; sign = "0"; tempString = "";
Label = ""; R = "";
txtDisplay.setText("0");
lblFirst.setText("_");
lblOperator.setText("?");
lblSecond.setText("_");
lblEqual.setText("=");
lblResult.setText("_");
number1 = 0.0; number2 = 0.0; result = 0.0;
decimalUsed = false; secondNum = false; makeSecondTrue = false;
lblSecondNum = false; secondEqual = false; error = false;
}
//Shows the About Calculator Dialog
public void showAboutDialog() {
/* JDialog(Frame, Title, boolean)
boolean: for if you want the dialog to be a pop-up so you
have to do something to make it go away or another kind of frame
beside your original frame. */
JDialog dlgAbout = new JDialog(window, "About Calculator", true);
JTextArea txtAbout = new JTextArea(4, 4);
txtAbout.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel pnlAbout = new JPanel(new FlowLayout(FlowLayout.CENTER));
String about;
about = "Calculator" + "\n\n" +
"Version: " + VERSION + "\n" +
"Created: August 7, 2008" + "\n" +
"Author: Blmaster";
txtAbout.setText(about);
txtAbout.setEditable(false);
txtAbout.setBackground(new Color(240, 240, 240));
pnlAbout.add(txtAbout);
pnlAbout.setBackground(Color.blue);
dlgAbout.add(pnlAbout);
dlgAbout.setSize(180, 122);
dlgAbout.setLocation(window.getX() + 60, window.getY() + 50);
dlgAbout.setResizable(false);
dlgAbout.setVisible(true);
}
/* Since you cant call a class (you can only call a method),
we have to make a instance of it. An example would be like,
you cant call a car so it magically appears in front of you,
but you can make a car. Something like that.
The "new" makes a new Calculator and pretty much calls
the code in the class contructor. */
public static void main(String[] args) {
new Calculator();
}
}
/*
Version Changes:
0.5- made basic layout of application.
1.0- added basic (/, *, -, +) operator functions.
1.1- added function: lets you keep calculating without hitting "=" button.
1.15- fixed bug: wouldnt work after first time.
1.2- added function: Clear button.
1.3- added function: Clear Exisiting button.
1.4- reorganized code: works more efficient now.
1.6- added function: change operator sign.
1.65- fixed bug: intefered with equal sign.
1.7- added function: MAX_INPUT for textbox
1.75- fixed bug: after textbox has reached MAX_INPUT, wouldnt work.
1.8- added function: Backspace button.
1.85- fixed (1.6) bug: 1.6 function wouldnt work after first use.
2.0- improved: error system, reorganized code, C, CE, Backspace Buttons.
2.1- added function: menu bar. Program --> Reset, Exit
2.2- added Help --> About to menu bar.
2.5- added View --> Show Calculations to menu bar. (beta)
2/6- replaced About with a Dialog Message.
2.7- fixed Show Calculations. (a lot of work)
2.8- reorganized code: show calculation function is cleaned to work more efficiently.
2.9- fixed bug: 0 button would add 0 in front of number. Ex. 032
2.95- fixed (1.8) bug: Backspace wouldnt make decimal work if it erases decimal.
2.99- fixed (2.5) bugs: another Show Calculation bug. wouldnt show 0.
3.0- Menu Bar, Show Calculation function, removed all the ".0" at end of number. STABLE
3.2- added (sqrt, %, 1/x, +/-) functions.
3.25- fixed bugs: 3.2 functions intefered with labels.
3.4- reorganized code: more methods for easier understanding.
3.5- added Key Listener: Numper Pad in keyboard works with Calculator.
3.55- fixed (3.2) bugs: you can start over after doing functions.
3.59- fixed bug: first number label always showing 0 with percent button.
3.6- fixed bug: sqrt function would display error as number.
3.65- fixed bug: the equal button would calculate wrongly when pressed twice in a row.
3.7- added function: forces user to clear or clear exisiting or reset to get out of error.
3.8- changed About dialog.
4.0- FINISHED
*/
Subscribe to:
Posts (Atom)