Home>

Write an application for an analog calculator,Using panels and grid layouts, Add a text box,10 number buttons (0 ~ 9), 4 addition, subtraction, multiplication and division buttons, An equal sign button,A clear button,A square root button,A backspace button, Require calculation formulas and results to be displayed in text boxes,The effect is shown in the following figure.

Java simple calculator code:

import javax.swing. *;
import javax.swing.jtextfield;
import java.awt. *;
import java.awt.event. *;
import java.lang. *;
import java.awt.color;
public class ex5_2 extends jframe implements actionlistener
{
  private jpanel p1=new jpanel ();// Create a panel
  private jpanel p2=new jpanel ();
  private jtextfield t1;// Text box 1 is used to display input information
  private jtextfield t2;// Text box 2 is used to display the result information
  private jlabel label;// label information
  stringbuffer str;// String displayed on the display
  double x, y;// x and y are both operands
  int z;// z indicates which operator was clicked.
0 means "+", 1 means "-", 2 means "*", and 3 means "/"
  private jbutton b []=new jbutton [12];// Create an array with 12 buttons
  private jbutton b1, b2, b3, b4, b5, b6, b7, b8;// arithmetic function button
  public ex5_2 ()
  {
    super ("Simple calculator");// Window name
    container c=getcontentpane ();// Create content panel object
    t1=new jtextfield (30);
    t1.seteditable (false);// Can only be displayed,Cannot edit
    t2=new jtextfield (30);
    t2.seteditable (false);// Can only be displayed,Cannot edit
    label=new jlabel ("Welcome to the Little Witch Calculator ^ _ ^ o ~ Work hard!");
    label.setforeground (color.blue);
    // Create an empty string buffer
    str=new stringbuffer ();
    p2.add (label);// Add label to panel
    p2.add (t2);// Add text box to panel
    p2.add (t1);// Add text box to panel
    p2.setlayout (new gridlayout (4,1));// lay out the surface to 4 rows and 1 column
    for (int i=0;i<10;i ++) // Set the labels for the buttons 0-9 in the array,And register the listener
    {
      string s="" + i;
      b [i]=new jbutton (s);
      b [i] .addactionlistener (this);
    }
    // Instantiate each button
    b [10]=new jbutton ("-/ +");b [11]=new jbutton (".");
    b1=new jbutton ("/");b2=new jbutton ("back");
    b3=new jbutton ("*");b4=new jbutton ("c");
    b5=new jbutton ("+");b6=new jbutton ("sqrt");
    b7=new jbutton ("-");b8=new jbutton ("=");
    // Set the button foreground color
    for (int i=0;i<12;i ++)
    {
      b [i] .setforeground (color.blue);
    }
    b1.setforeground (color.red);b3.setforeground (color.red);
    b5.setforeground (color.red);b7.setforeground (color.red);
    b2.setforeground (color.blue);b4.setforeground (color.blue);
    b6.setforeground (color.red);b8.setforeground (color.blue);
    // Add to panel
    p1.add (b [7]);p1.add (b [8]);p1.add (b [9]);p1.add (b1);p1.add (b2);
    p1.add (b [4]);p1.add (b [5]);p1.add (b [6]);p1.add (b3);p1.add (b4);
    p1.add (b [1]);p1.add (b [2]);p1.add (b [3]);p1.add (b5);p1.add (b6);
    p1.add (b [0]);p1.add (b [10]);p1.add (b [11]);p1.add (b7);p1.add (b8);
    p1.setlayout (new gridlayout (4,5,5,5));
    // Register the listener
    b [10] .addactionlistener (this);b [11] .addactionlistener (this);
    b1.addactionlistener (this);b2.addactionlistener (this);
    b3.addactionlistener (this);b4.addactionlistener (this);
    b5.addactionlistener (this);b6.addactionlistener (this);
    b7.addactionlistener (this);b8.addactionlistener (this);
    // Add the panel to the content panel
    c.add (p2);
    c.add (p1);
    c.setlayout (new flowlayout ());// Set to sequential layout
    setdefaultcloseoperation (jframe.exit_on_close);// Set window close action
    setvisible (true);// Set as visible
    setresizable (false);// Prohibit resizing the frame
    setsize (400,300);// Set the window size
  }
  // The main method implements creating a window
  public static void main (string [] args)
  {ex5_2 f=new ex5_2 ();}
  // Event handling of the button
  public void actionperformed (actionevent e)
  {
  try
  {
    if (e.getsource () == b4) // Select "c" to clear
    {
      t1.settext ("0");// zero the text box
      t1.sethorizontalalignment (jtextfield.right);// right of text alignment
      str.setlength (0);// Empty the string buffer in preparation for receiving new input operands
    }
    else if (e.getsource () == b [10]) // Click "+/-" to select whether the input operand is positive or negative
    {
      x=double.parsedouble (t1.gettext (). trim ());// trim function is to remove spaces in the string
      t1.settext ("" + (-x));
      t1.sethorizontalalignment (jtextfield.right);
    }
    else if (e.getsource () == b5) // Click the plus button to get the value of x and z and clear the value of y
    {
      x=double.parsedouble (t1.gettext (). trim ());
      str.setlength (0);
      y=0d;
      z=0;
    }
    else if (e.getsource () == b7) // click the minus button to get the value of x and z and clear the value of y
    {
      x=double.parsedouble (t1.gettext (). trim ());
      str.setlength (0);
      y=0d;
      z=1;
    }
    else if (e.getsource () == b3) // Click the multiplication button to get the value of x and z and clear the value of y
    {
      x=double.parsedouble (t1.gettext (). trim ());
      str.setlength (0);
      y=0d;
      z=2;
    }
    else if (e.getsource () == b1) // Click the divide button to get the value of x and z and clear the value of y
    {
      x=double.parsedouble (t1.gettext (). trim ());
      str.setlength (0);
      y=0d;
      z=3;
    }
    else if (e.getsource () == b8) // Click the equal sign button to output the calculation result
    {
      str.setlength (0);
      switch (z)
      {
        case 0:t1.settext ("" + (x + y));t1.sethorizontalalignment (jtextfield.right);break;
        case 1:t1.settext ("" + (x-y));t1.sethorizontalalignment (jtextfield.right);break;
        case 2:t1.settext ("" + (x * y));t1.sethorizontalalignment (jtextfield.right);break;
        case 3:t1.settext ("" + (x/y));t1.sethorizontalalignment (jtextfield.right);break;
      }
    }
    else if (e.getsource () == b [11]) // click the "." button to enter a decimal
    {
      if (t1.gettext (). trim (). indexof (".")! =-1)
      {
      }
      else // if there is no decimal point
      {
        if (t1.gettext (). trim (). equals ("0")) // if initially displayed as 0
        {
          t1.settext (str.append (e.getactioncommand ()). tostring ());
          t1.sethorizontalalignment (jtextfield.right);
        }
        else if (t1.gettext (). trim (). equals ("")) // Do nothing if it is initially empty
        {}
        else
        {
          t1.settext (str.append (e.getactioncommand ()). tostring ());
          t1.sethorizontalalignment (jtextfield.right);
        }
      }
    y=0d;
    }
    else if (e.getsource () == b6) // Find the square root
    {
      x=double.parsedouble (t1.gettext (). trim ());
      if (x<0)
      {
        t1.settext ("The number format is abnormal");
        t1.sethorizontalalignment (jtextfield.right);
      }
      else
      {
        t1.settext ("" + math.sqrt (x));
        t1.sethorizontalalignment (jtextfield.right);
      }
      str.setlength (0);
      y=0d;
    }
    else
    {
      if (e.getsource () == b [0]) // If the number key "0" is selected
      {
        if (t1.gettext (). trim (). equals ("0")) // Do nothing if the display shows zero
        {}
        else
          t1.settext (str.append (e.getactioncommand ()). tostring ());
          t1.sethorizontalalignment (jtextfield.right);
          y=double.parsedouble (t1.gettext (). trim ());
      }
      else if (e.getsource () == b2) // Select the back key
      {
        if (! t1.gettext (). trim (). equals ("0")) // if the display is not zero
        {
        if (str.length ()!=1)
        {
          t1.settext (str.delete (str.length ()-1, str.length ()). tostring ());// It may throw a string out of bounds exception
          t1.sethorizontalalignment (jtextfield.right);
        }
        else
        {
          t1.settext ("0");t1.sethorizontalalignment (jtextfield.right);
          str.setlength (0);
        }
      }
      y=double.parsedouble (t1.gettext (). trim ());
      }
      else
        {
        t1.settext (str.append (e.getactioncommand ()). tostring ());
        t1.sethorizontalalignment (jtextfield.right);
        y=double.parsedouble (t1.gettext (). trim ());
        }
      }
    }
    catch (numberformatexception e1) {t1.settext ("Number formatexception");
    t1.sethorizontalalignment (jtextfield.right);}
    catch (stringindexoutofboundsexception e1) {t1.settext ("String indexoutofboundsexception");
    t1.sethorizontalalignment (jtextfield.right);}
  }
}

Operation effect diagram:

A java simple calculator program design is completed,I hope this article can be an inspiration for everyone to write a calculator,This is just a simple calculator,Everyone can continue to play,Improve calculator function.

  • Previous Summary of PHP and Mysql transit UTF8 encoding problems
  • Next JavaScript regular expressions and strings RegExp and String (two)