Java Instance---calculator instance

Source: Internet
Author: User
Tags arithmetic event listener gettext square root

1. The display name of the key on the calculator

1.0 Inheritance JFrame class

Public class Calculate extends JFrame {

}

1.1 Defining constants

The display name of the key on the/** calculator */

Public Final String[] KEYS = {"7", "8", "9", "/", "sqrt", "4", "5", "6", "*", "%", "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "= " };

The display name of the function key on the/** calculator */

Public Final String[] COMMAND = {"Backspace", "CE", "C"};

/** the display name of the m on the left of the calculator */

Private Final String[] M = {"", "MC", "MR", "MS", "m+"};

1.2 open space for the corresponding keys

/** the function button on the calculator */

Private JButton commands[] = new Jbutton[command.length];

/** Calculator to the left of the M button */

Private JButton m[] = new Jbutton[m.length];

/** Calculation result text box */

Private JTextField Resulttext = new JTextField ("0");

1.3 Final:

2 Internal Layout code 2.1 Key Button code

Initialize the button on the Calculator key and place the key in an artboard

JPanel Keypanel = new JPanel ();

With Grid layout, 4 rows, 5 columns of grid, horizontal between the grid is 3 pixels, the vertical interval is 3 pixels

Keypanel.setlayout (new GridLayout (4, 5, 3, 3));

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

The numbers are placed in the button

Keys[i] = new JButton (Keys[i]);

Add a key to the panel

Keypanel.add (Keys[i]);

Set Color to light blue

Keys[i].setforeground (Color. Blue);

}

Operator keys are marked in red, and others are shown in blue

Keys[3].setforeground (Color. Red);

Keys[8].setforeground (Color. Red);

Keys[13].setforeground (Color. Red);

Keys[18].setforeground (Color. Red);

Keys[19].setforeground (Color. Red);

2.2 Initializing the function key code

The initialization function keys are marked in red. Place function keys inside an artboard

JPanel Commandspanel = new JPanel ();

With grid layout, 1 rows, 3 columns of grid, horizontal between the grid is 3 pixels, the vertical interval is 3 pixels

Commandspanel.setlayout (new GridLayout (1,3,3,3));

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

Commands[i] = new JButton (Command[i]);

Commandspanel.add (Commands[i]);

Commands[i].setforeground (Color. Red);

}

2.3 Initialize m key code

Initialize M key, mark with red, put M key inside an artboard

JPanel Calmspanel = new JPanel ();

Calmspanel.setlayout (new GridLayout (5,1,3,3));

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

M[i] = new JButton (M[i]);

Calmspanel.add (M[i]);

M[i].setforeground (Color. Red);

}

2.3 Setting the text box code

Right-aligned content in text box

Resulttext.sethorizontalalignment (JTextField. right);

Modify result text box is not allowed

Resulttext.seteditable (false);

Set text box background color to White

Resulttext.setbackground (Color. white);

2.4 Overall layout code

JPanel Panel1 = new JPanel ();

The artboard uses the boundary layout manager, and the horizontal and vertical intervals between components in the artboard are 3 pixels

Panel1.setlayout (new BorderLayout (3, 3));

Panel1.add ("Center", Keypanel);

Panel1.add ("North", Commandspanel);

Create an artboard to place a text box

JPanel top = new JPanel ();

Top.setlayout (new borderlayout ());

Top.add ("Center", Resulttext);

Overall layout

The horizontal interval between components in the artboard is 3 pixels, and the vertical interval is 5 pixels.

Getcontentpane (). setlayout (new BorderLayout (3, 5));

Getcontentpane (). Add ("North", top);

Getcontentpane (). Add ("Center", Panel1);

Getcontentpane (). Add ("West", Calmspanel);

2.5 Adding event listeners

Implementation of ActionListener class, replication Actionperformed method

Public class Test1 extends JFrame implements ActionListener { ...

Add event listeners for each button

Use the same event listener, which is this object. The declaration of this class has implements ActionListener

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

Keys[i].addactionlistener (this);

}

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

Commands[i].addactionlistener (this);

}

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

M[i].addactionlistener (this);

}

}

2.6 Handling a fallback event

/** handling the event that the BACKSPACE key was pressed */

Private void Handlebackspace () {

Get the contents of a text box

String text = Resulttext.gettext ();

int len = text.length ();

if (Len > 0) {

Indicates that there is a number write

Text = text.substring (0, len-1);

if (text.length () = = 0) {

If the text does not have content, initialize the various values of the calculator

Resulttext.settext ("0");

}Else{

Resulttext.settext (text);

}

}

2.7 handling CE keys

The user presses the "CE" key

Resulttext.settext ("0");

2.8 Handling Numbers

Define variables:

Flag whether the user presses the first number of the entire expression, or the first number after the operator

Private Boolean Firstdigit = true;

/**

* Handle the event that the numeric key is pressed

*/

Private void handlenumber (String label) {

Firstdigit default is True

if (Firstdigit) {

The user presses the first one is the number

Resulttext.settext (label);

}Else if((Label.equals (")") && (Resulttext.gettext (). IndexOf (".") < 0)) {

The decimal point is entered, and there is no previous decimal point, the decimal point is appended to the result text box

Resulttext.settext (Resulttext.gettext () + ".");

}Else if(! label.equals (".")) {

If the input is not a decimal point, the number is appended to the result text box

Resulttext.settext (Resulttext.gettext () + label);

}

It's definitely not the first number to be entered later.

Firstdigit = false;

}

2.9 Handling an event where the operator keys are pressed

0. Set whether the operation is normal flag bit Operatevalidflag = True

Set intermediate variable resultnum = 0.0

Set operator variable operator = "" Main Number gets the number displayed on the current page

1. "=" is primarily used to display numbers, which can be the number currently entered,

It can also be a number assigned to the interface after counting.

2. Assign the current operation symbol to the variable operator

3. Set firstdigt = True for the next screen display

Operators for the current operation

Private String operator = "=";

Set a flag bit to determine whether it is legal

Private boolean Operatevalidflag = true;

The intermediate result of the calculation.

Private double resultnum = 0.0;

* Handling events where operator keys are pressed

* @param key

*/

Private void handleoperator (String label) {

Division operation

if (Operator.equals ("/")) {

if (Getnumberfromtext () = = 0.0) {

Operation not valid

Operatevalidflag = false;

Resulttext.settext ("Divisor cannot be zero");

} Else {

Resultnum/= Getnumberfromtext ();

}

Inverse arithmetic

} Else if (operator.equals ("1/x")) {

if (Resultnum = = 0.0) {

Operatevalidflag = false;

Resulttext.settext ("Divisor cannot be zero");

} Else {

Resultnum = 1/resultnum;

}

} Else if (operator.equals ("+")) {

Addition operation

Resultnum + = Getnumberfromtext ();

} Else if (Operator.equals ("-")) {

Subtraction operations

Resultnum-= Getnumberfromtext ();

} Else if (operator.equals ("*")) {

Multiplication operations

Resultnum *= Getnumberfromtext ();

} Else if (operator.equals ("sqrt")) {

Radical operation

Resultnum = Math. sqrt (Resultnum);

} Else if (operator.equals ("+/-")) {

Positive negative number arithmetic

Resultnum = Resultnum * (-1);

} Else if (operator.equals ("=")) {

Assignment operations

Resultnum = Getnumberfromtext ();

}

if (Operatevalidflag) {

Operation of double-precision floating-point numbers

long t1;

double T2;

T1 = (long) resultnum;

t2 = resultnum-t1;

if (t2 = = 0) {

Resulttext.settext (String. ValueOf(t1));

System. out. println ("Resulttext.settext (string.valueof (T1))" + String. ValueOf(t1));

}Else{

Resulttext.settext (String. ValueOf(resultnum));

System. out. println ("Resulttext.settext (string.valueof (Resultnum))" + String. ValueOf(resultnum));

}

}

Operator equals the button that the user presses

operator = label;

Firstdigit = true;

Operatevalidflag = true;

}

/**

* Get numbers from the result text box

*/

Private double Getnumberfromtext () {

double result = 0;

result = Double. valueOf (Resulttext.gettext ());

return result;

}

2.10 handling C keys

/**

* Handle the event that the C key is pressed

*/

Private void Handlec () {

Initialize the various values of the calculator

Resulttext.settext ("0");

This.firstdigit = true;

}

3 complete code included:

Package test;

Import Java.awt.BorderLayout;

Import Java.awt.Color;

Import Java.awt.GridLayout;

Import java.awt.event.ActionEvent;

Import Java.awt.event.ActionListener;

Import Javax.swing.JButton;

Import Javax.swing.JFrame;

Import Javax.swing.JPanel;

Import Javax.swing.JTextField;

/**

* A calculator, similar to the Standard Edition function and interface of the Windows accessory comes with calculator. However, keyboard operation is not supported.

*/

public class T extends JFrame implements ActionListener {

The display name of the key on the/** calculator */

Private final string[] KEYS = {"7", "8", "9", "/", "sqrt", "4", "5", "6",

"*", "%", "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "="};

The display name of the function key on the/** calculator */

Private final string[] COMMAND = {"Backspace", "CE", "C"};

/** the display name of the m on the left of the calculator */

Private final string[] M = {"", "MC", "MR", "MS", "m+"};

/** button on the calculator */

Private JButton keys[] = new Jbutton[keys.length];

/** the function button on the calculator */

Private JButton commands[] = new Jbutton[command.length];

/** Calculator to the left of the M button */

Private JButton m[] = new Jbutton[m.length];

/** Calculation result text box */

Private JTextField Resulttext = new JTextField ("0");

Flag whether the user presses the first number of the entire expression, or the first number after the operator

Private Boolean firstdigit = true;

The intermediate result of the calculation.

Private double resultnum = 0.0;

Operators for the current operation

Private String operator = "=";

Whether the operation is legal

Private Boolean operatevalidflag = true;

/**

* Constructor function

*/

Public T () {

Super ();

Initialize Calculator

Init ();

Set the background color of the calculator

This.setbackground (Color.light_gray);

This.settitle ("calculator");

Display calculator at screen (500, 300) coordinates

This.setlocation (500, 300);

Don't change the size of the calculator

This.setresizable (FALSE);

Make the components of the calculator fit in size

This.pack ();

}

/**

* Initialize Calculator

*/

private void init () {

Right-aligned content in text box

Resulttext.sethorizontalalignment (Jtextfield.right);

Modify result text box is not allowed

Resulttext.seteditable (FALSE);

Set text box background color to White

Resulttext.setbackground (Color.White);

Initialize the button on the Calculator key and place the key in an artboard

JPanel Calckeyspanel = new JPanel ();

With Grid layout, 4 rows, 5 columns of grid, horizontal between the grid is 3 pixels, the vertical interval is 3 pixels

Calckeyspanel.setlayout (New GridLayout (4, 5, 3, 3));

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

Keys[i] = new JButton (keys[i]);

Calckeyspanel.add (Keys[i]);

Keys[i].setforeground (Color.Blue);

}

Operator keys are marked in red, and others are shown in blue

Keys[3].setforeground (color.red);

Keys[8].setforeground (color.red);

Keys[13].setforeground (color.red);

Keys[18].setforeground (color.red);

Keys[19].setforeground (color.red);

The initialization function keys are marked in red. Place function keys inside an artboard

JPanel Commandspanel = new JPanel ();

With grid layout, 1 rows, 3 columns of grid, horizontal between the grid is 3 pixels, the vertical interval is 3 pixels

Commandspanel.setlayout (New GridLayout (1, 3, 3, 3));

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

Commands[i] = new JButton (Command[i]);

Commandspanel.add (Commands[i]);

Commands[i].setforeground (color.red);

}

Initialize M key, mark with red, put M key inside an artboard

JPanel Calmspanel = new JPanel ();

Grid layout manager, 5 rows, 1 columns of grid, horizontal between the grid between 3 pixels, vertical interval of 3 pixels

Calmspanel.setlayout (New GridLayout (5, 1, 3, 3));

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

M[i] = new JButton (M[i]);

Calmspanel.add (M[i]);

M[i].setforeground (color.red);

}

The overall layout of the calculator is shown below, and the Calckeys and command Artboards are placed in the middle of the calculator,

Place the text box in the north and place the calms artboard in the west of the calculator.

Create a large artboard, and place the command and Calckeys artboard created above in the artboard

JPanel Panel1 = new JPanel ();

The artboard uses the boundary layout manager, with 3 pixels spaced between the components in the artboard in both horizontal and vertical directions.

Panel1.setlayout (New BorderLayout (3, 3));

Panel1.add ("North", Commandspanel);

Panel1.add ("Center", Calckeyspanel);

Create an artboard to place a text box

JPanel top = new JPanel ();

Top.setlayout (New BorderLayout ());

Top.add ("Center", Resulttext);

Overall layout

Getcontentpane (). setlayout (New BorderLayout (3, 5));

Getcontentpane (). Add ("North", top);

Getcontentpane (). Add ("Center", Panel1);

Getcontentpane (). Add ("West", Calmspanel);

Add event listeners for each button

Use the same event listener, which is this object. The declaration of this class has implements ActionListener

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

Keys[i].addactionlistener (this);

}

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

Commands[i].addactionlistener (this);

}

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

M[i].addactionlistener (this);

}

}

/**

* Handling Events

*/

public void actionperformed (ActionEvent e) {

Gets the label of the event source

String label = E.getactioncommand ();

if (Label.equals (Command[0])) {

The user pressed the "Backspace" key

Handlebackspace ();

} else if (Label.equals (command[1])) {

The user presses the "CE" key

Resulttext.settext ("0");

} else if (Label.equals (command[2])) {

The user pressed the "C" key

Handlec ();

} else if ("0123456789."). IndexOf (label) >= 0) {

The user presses the number key or the decimal key

Handlenumber (label);

Handlezero (zero);

} else {

The user presses the operator key

Handleoperator (label);

}

}

/**

* Handling the event that the BACKSPACE key is pressed

*/

private void Handlebackspace () {

String text = Resulttext.gettext ();

int i = Text.length ();

if (i > 0) {

Backspace to remove the last character of the text

Text = text.substring (0, i-1);

if (text.length () = = 0) {

If the text does not have content, initialize the various values of the calculator

Resulttext.settext ("0");

Firstdigit = true;

operator = "=";

} else {

Display the new text

Resulttext.settext (text);

}

}

}

/**

* Handle the event that the numeric key is pressed

*

* @param key

*/

private void Handlenumber (String key) {

if (firstdigit) {

The first number entered

Resulttext.settext (key);

} else if ((Key.equals (")") && (Resulttext.gettext (). IndexOf (".") < 0)) {

The decimal point is entered, and there is no previous decimal point, the decimal point is appended to the result text box

Resulttext.settext (Resulttext.gettext () + ".");

} else if (!key.equals (".")) {

If the input is not a decimal point, the number is appended to the result text box

System.out.println ("Resulttext.gettext ()" + Resulttext.gettext ());

Resulttext.settext (Resulttext.gettext () + key);

System.out.println ("Resulttext.gettext ()" + resulttext.gettext () + key);

}

It's definitely not the first number to be entered later.

Firstdigit = false;

}

/**

* Handle the event that the C key is pressed

*/

private void Handlec () {

Initialize the various values of the calculator

Resulttext.settext ("0");

Firstdigit = true;

operator = "=";

}

/**

* Handling events where operator keys are pressed

*/

private void Handleoperator (String key) {

System.out.println (Operator.equals ("/"));

if (Operator.equals ("/")) {

System.out.println ("Enter into Division");

Division operation

If the value in the current result text box equals 0

if (getnumberfromtext () = = 0.0) {

Operation not valid

Operatevalidflag = false;

Resulttext.settext ("Divisor cannot be zero");

} else {

System.out.println ("Resultnum:" + resultnum);

Resultnum/= Getnumberfromtext ();

System.out.println ("Resultnum/= Getnumberfromtext ():" + resultnum);

}

} else if (Operator.equals ("1/x")) {

Inverse arithmetic

if (Resultnum = = 0.0) {

Operation not valid

Operatevalidflag = false;

Resulttext.settext ("0 no reciprocal");

} else {

Resultnum = 1/resultnum;

}

} else if (operator.equals ("+")) {

Addition operation

Resultnum + = Getnumberfromtext ();

} else if (Operator.equals ("-")) {

Subtraction operations

Resultnum-= Getnumberfromtext ();

} else if (Operator.equals ("*")) {

Multiplication operations

Resultnum *= Getnumberfromtext ();

} else if (Operator.equals ("sqrt")) {

Square root operation

Resultnum = Math.sqrt (resultnum);

} else if (operator.equals ("%")) {

Percent percent operation, divided by 100

Resultnum = resultnum/100;

} else if (operator.equals ("+/-")) {

Positive negative number arithmetic

Resultnum = Resultnum * (-1);

} else if (operator.equals ("=")) {

Assignment operations

Resultnum = Getnumberfromtext ();

}

if (Operatevalidflag) {

Operation of double-precision floating-point numbers

Long T1;

Double T2;

T1 = (long) resultnum;

SYSTEM.OUT.PRINTLN (t1);

t2 = resultnum-t1;

System.out.println (T2);

if (t2 = = 0) {

Resulttext.settext (string.valueof (t1));

} else {

Resulttext.settext (string.valueof (resultnum));

System.out.println ("Resulttext.settext (string.valueof (Resultnum))" + string.valueof (resultnum));

}

}

Operator equals the button that the user presses

operator = key;

Firstdigit = true;

Operatevalidflag = true;

}

/**

* Get numbers from the result text box

*

* @return

*/

Private double Getnumberfromtext () {

Double result = 0;

try {

result = Double.valueof (Resulttext.gettext ()). Doublevalue ();

} catch (NumberFormatException e) {

}

return result;

}

public static void Main (String args[]) {

T Calculator1 = new T ();

Calculator1.setvisible (TRUE);

Calculator1.setdefaultcloseoperation (Jframe.exit_on_close);

}

}

Java Instance---calculator instance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.