Swing Implementation Calculator

Source: Internet
Author: User

The code is as follows

Import Java.awt.*;import java.awt.event.*;import Javax.swing.*;import Java.util.vector;public class Calculator {Strin G str1 = "0"; Operand 1 Initial value must be 0 for program security String str2 = "0"; Operand 2 String signal = "+"; Operator String result = "";//result//status switch int k1 = 1;//switch 1 used to select input direction to be written to str2 or str2 int k2 = 1;//Switch 2 sign key number k2& Gt;1 instructions are 2+3-9+8 such a multi-sign operation int K3 = 1;//Switch 3 str1 can be cleared 0 ==1 when!=1 can not be cleared 0 int K4 = 1;//Switch 4 str2 Ibid int K5 = 1;/ /Switch 5 control the decimal point can be entered ==1!=1 input decimal point is discarded JButton store;    Register record whether the symbol key is pressed continuously @SuppressWarnings ("rawtypes") vector vt = new vector (20, 10);    JFrame frame = new JFrame ("Calculator");    JTextField Result_textfield = new JTextField (result, 20);//20 columns JButton Clear_button = new JButton ("clear");    JButton button0 = new JButton ("0");    JButton button1 = new JButton ("1");    JButton button2 = new JButton ("2");    JButton Button3 = new JButton ("3");    JButton button4 = new JButton ("4");    JButton button5 = new JButton ("5"); JButton button6 = new JButton ("6");    JButton button7 = new JButton ("7");    JButton button8 = new JButton ("8");    JButton Button9 = new JButton ("9");    JButton Button_dian = new JButton (".");    JButton Button_jia = new JButton ("+");    JButton Button_jian = new JButton ("-");    JButton Button_cheng = new JButton ("*");    JButton Button_chu = new JButton ("/");    JButton button_dy = new JButton ("="); Calculator () {button0.setmnemonic (KEYEVENT.VK_0);//equivalent key//other equivalent key, Result_textfield.sethorizontala        Lignment (jtextfield.right);//text box right-aligned JPanel pan = new JPanel ();        Pan.setlayout (New GridLayout (4, 4, 5, 5));//Four rows four row margin is 5 pixels pan.add (button7);        Pan.add (BUTTON8);        Pan.add (BUTTON9);        Pan.add (Button_chu);        Pan.add (BUTTON4);        Pan.add (BUTTON5);        Pan.add (BUTTON6);        Pan.add (Button_cheng);        Pan.add (button1);        Pan.add (button2);        Pan.add (Button3);        Pan.add (Button_jian);        Pan.add (Button0); PAn.add (Button_dian);        Pan.add (Button_dy);        Pan.add (Button_jia);        Pan.setborder (Borderfactory.createemptyborder (5, 5, 5, 5));//Pan object margin JPanel pan2 = new JPanel ();        Pan2.setlayout (New BorderLayout ());        Pan2.add (Result_textfield, borderlayout.west);        Pan2.add (Clear_button, borderlayout.east); Frame.setlocation (300, 200); The main window appears in position frame.setresizable (false);        Cannot adjust size frame.getcontentpane (). setlayout (New BorderLayout ());        Frame.getcontentpane (). Add (pan2, Borderlayout.north);        Frame.getcontentpane (). Add (pan, borderlayout.center);        Frame.pack ();        Frame.setvisible (TRUE);            Event handler//numeric key class Listener implements ActionListener {@SuppressWarnings ("unchecked")                public void actionperformed (ActionEvent e) {String SS = ((JButton) E.getsource ()). GetText ();                store = (JButton) e.getsource ();             Vt.add (store);   if (k1 = = 1) {if (K3 = = 1) {str1 = "";                    K5 = 1;//restore switch K5 status} str1 = str1 + ss;                    K3 = K3 + 1;                        Result_textfield.settext (STR1);//display} else if (k1 = = 2) {if (K4 = = 1) {                        STR2 = ""; K5 = 1;                    Restore switch K5 status} str2 = str2 + ss;                    K4 = K4 + 1;                Result_textfield.settext (STR2); }}}//Symbol class Listener_signal implements ActionListener {@SuppressWarning S ("unchecked") public void actionperformed (ActionEvent e) {String SS2 = ((JButton) E.getsource (                ). GetText ();                store = (JButton) e.getsource ();                Vt.add (store);    if (K2 = = 1) {k1 = 2;//switch K1 is 1 o'clock, number 1 writes to 2 o'clock, writes to number 2                K5 = 1;                    signal = SS2;                    K2 = K2 + 1;//by the number of symbol keys} else {int a = Vt.size ();                    JButton C = (JButton) vt.get (a-2); if (! ( C.gettext (). Equals ("+")) &&! (C.gettext (). Equals ("-")) &&! (C.gettext (). Equals ("*")) &&!                    (C.gettext (). Equals ("/")))                        {cal ();                        STR1 = result;                        K1 = 2;//switch K1 is 1 o'clock, to the number 1 written as 2 o'clock, to the number 2 write K5 = 1;                        K4 = 1;                    signal = SS2;                } K2 = k2 + 1; }}}//Clear class Listener_clear implements ActionListener {@SuppressWarnings ( "Unchecked") public void actionperformed (ActionEvent e) {store = (JButton)E.getsource ();                Vt.add (store);                K5 = 1;                K2 = 1;                K1 = 1;                K3 = 1;                K4 = 1;                STR1 = "0";                STR2 = "0";                signal = "";                result = "";                Result_textfield.settext (result);            Vt.clear ();            }}//Equals class Listener_dy implements ActionListener {@SuppressWarnings ("unchecked")                public void actionperformed (ActionEvent e) {store = (JButton) e.getsource ();                Vt.add (store);                Cal (); K1 = 1;                Reset switch K1 status//Str1=result;                K2 = 1; K3 = 1;//restore switch K3 status K4 = 1; Reset switch K4 Status str1 = result;            Prepare for 7+5=12 +5=17 This calculation}}//Decimal class Listener_xiaos implements ActionListener { @SuppressWarnings ("unchecked") public VOID actionperformed (ActionEvent e) {store = (JButton) e.getsource ();                Vt.add (store);                    if (K5 = = 1) {String SS2 = ((JButton) E.getsource ()). GetText ();                            if (k1 = = 1) {if (K3 = = 1) {str1 = ""; K5 = 1;                        Restore switch K5 status} str1 = str1 + ss2;                        K3 = K3 + 1;                            Result_textfield.settext (STR1);//display} else if (k1 = = 2) {if (K4 = = 1) {                            STR2 = ""; K5 = 1;                        Restore switch K5 status} str2 = str2 + ss2;                        K4 = K4 + 1;                    Result_textfield.settext (STR2);            }} K5 = K5 + 1; }}//Register listener Listener_dy Jt_dy = new Listener_DY (); Listener JT = new Listener ()//pro-listening number key listener_signal jt_signal = new listener_signal ();//pro-listening symbol key Listener_ Clear Jt_c = new Listener_clear ();        Clear key Listener_xiaos Jt_xs = new Listener_xiaos ();//Decimal Key Button7.addactionlistener (JT);        Button8.addactionlistener (JT);        Button9.addactionlistener (JT);        Button_chu.addactionlistener (jt_signal);        Button4.addactionlistener (JT);        Button5.addactionlistener (JT);        Button6.addactionlistener (JT);        Button_cheng.addactionlistener (jt_signal);        Button1.addactionlistener (JT);        Button2.addactionlistener (JT);        Button3.addactionlistener (JT);        Button_jian.addactionlistener (jt_signal);        Button0.addactionlistener (JT);        Button_dian.addactionlistener (JT_XS);        Button_dy.addactionlistener (Jt_dy);        Button_jia.addactionlistener (jt_signal);        Clear_button.addactionlistener (Jt_c); Shutdown event handler Frame.addwindowlistener (new WIndowadapter () {public void windowclosing (WindowEvent e) {system.exit (0);    }        });        }//Calculate public void cal () {Double a2;//operand 1 double b2;//operand 2 String c = signal;//operator        Double RESULT2 = 0;//result if (C.equals ("")) {Result_textfield.settext ("enter operator");            } else {if (Str1.equals ("."))///string "." Error when converting to double type data so manual turn str1 = "0.0";                if (Str2.equals ("."))            str2 = "0.0";            A2 = double.valueof (str1). Doublevalue ();            B2 = double.valueof (str2). Doublevalue ();            if (c.equals ("+")) {result2 = a2 + b2;            } if (C.equals ("-")) {result2 = A2-B2;            } if (C.equals ("*")) {result2 = a2 * B2;                } if (C.equals ("/")) {if (B2 = = 0) {result2 = 0;               } else {     RESULT2 = A2/B2;            }} result = ((New Double (RESULT2)). toString ());        Result_textfield.settext (result);                    }} @SuppressWarnings ("unused") public static void main (string[] args) {//interface style, you can remove try {        Uimanager.setlookandfeel ("Com.sun.java.swing.plaf.windows.WindowsLookAndFeel");        } catch (Exception e) {e.printstacktrace ();    } Calculator cal = new Calculator (); }}

Detailed instructions in the Java Tutorial Web

Swing Implementation Calculator

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.