advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement


Java Boutique : Applet Categories : Educational : Calculators/Data Plotters

AwtCalc Source code


//==============================================================================
// Name:    AwtCalc.java
// version: 1.1
// Author:  Ernest Criss Jr.
// Created: January 4, 2001
//
// Anyone may use or rewrite this program in any way as long as proper credit is
// given to the original author.
//==============================================================================
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

index.html

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 DevX Skillbuilding from IBM developerWorks
 RIA Run Contest: Build Next-Gen Apps in Microsoft Silverlight 2
 Avaya DevConnect Center
 Intel Go Parallel Portal
 Internet.com eBook Library
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 53
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

SaaS Tool Offers Custom Database Development
Microsoft’s Automated Agent: Can We Talk?
Borland Finally Sells CodeGear
Red Hat Heads For The JON 2.0
Out with the Old, in with the New at JavaOne
Trolltech Expands WebKit Footprint
Oracle: Eating its Own Open Source Food
Big Money and Open Source May Not Compute
Open Source Embrace Gives Sun New Fans
NetBeans, OpenSolaris Also in Spotlight at JavaOne

Taming Trees: Building Branching Structures
Clean Up Function Syntax Mess with decltype
Sutter Speaks: The Future of Concurrency
INTEL SCAVENGER HUNT, LENOVO X300 AND APPLE IPOD TOUCH GIVEAWAY (the "Giveaway")
Comparing Multi-Core Processors for Server Virtualization
Intel® Desktop Business Computing Solutions
Intel: What Downturn?
Managing the Evolving Data Center
Implement Drag and Drop in Your Windows Forms Applications
Processing Linked Web Data with XSLT

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES