Package me. jerrys. calc; Import java. awt. FlowLayout; Import java. awt. Font; Import java. awt. GridLayout; Import java. awt. KeyEventPostProcessor; Import java. awt. KeyboardFocusManager; Import java. awt. event. ActionEvent; Import java. awt. event. ActionListener; Import java. awt. event. KeyEvent; Import java. util. HashMap; Import javax. swing. JButton; Import javax. swing. JFrame; Import javax. swing. JLabel; Import javax. swing. JOptionPane; Import javax. swing. JPanel; @ SuppressWarnings ("serial ") Public class CalcUI extends JFrame implements ActionListener { Private CalcAction action; Public HashMap <Integer, String> actionsMap = new HashMap <Integer, String> (); Public HashMap <String, JButton> buttonMap = new HashMap <String, JButton> (); Public JLabel rusultLabel; Public CalcUI (CalcAction action ){ Super ("simple calculator-Coded by JerryLocke "); This. action = action; CreateUI (); ShowMessage ("Java simple calculator n author @ JerryLocken blog http://111CN.NETn prompts you can use the keyboard for operations "); } Public void createUI (){ RusultLabel = new JLabel ("0 "); RusultLabel. setFont (new Font ("Arial", 0, 32 )); JPanel topPanel = new JPanel (); TopPanel. add (rusultLabel ); TopPanel. setLayout (new FlowLayout (FlowLayout. RIGHT )); JPanel numberPanel = new JPanel (new GridLayout (4, 3, 5, 5 )); String [] [] numberTitle = {"7" },{ "8" },{ "9" },{ "4" },{ "5 "}, {"6" },{ "1" },{ "2" },{ "3" },{ "0 "},{". "," decimal point "},{" +/-"," positive/negative "}}; BatchCreateButton (numberTitle, numberPanel, this ); JPanel calc1Panel = new JPanel (new GridLayout (2, 2, 5, 5 )); String [] [] calc1Title = {"& larr;", "return" },{ "C", "clear" },{ "×", "multiply "}, {"other", ""}}; BatchCreateButton (calc1Title, calc1Panel, this ); JPanel calc2Panel = new JPanel (new GridLayout (2, 1, 5, 5 )); String [] [] calc2Title = {"-", "subtract" },{ "=", "equals "}}; BatchCreateButton (calc2Title, calc2Panel, this ); TopPanel. setBounds (5, 0,330, 50 ); NumberPanel. setBounds (5, 50,200,313 ); Calc1Panel. setBounds (210, 51,130,153 ); Calc2Panel. setBounds (277,209, 62,153 ); JButton calcButton = createButton ("+", this ); CalcButton. setBounds (210,209, 62,153 ); CalcButton. setFont (new Font ("Arial", 0, 20 )); This. setLayout (null ); This. add (topPanel ); This. add (numberPanel ); This. add (calc1Panel ); This. add (calc2Panel ); This. add (calcButton ); This. setSize (350,400 ); KeyboardFocusManager manager = KeyboardFocusManager. getCurrentKeyboardFocusManager (); Manager. addKeyEventPostProcessor (new KeyEventPostProcessor (){ Public boolean postProcessKeyEvent (KeyEvent e ){ If (e. getID () = KeyEvent. KEY_RELEASED ){ String key = "-1 "; Switch (e. getKeyCode ()){ Case KeyEvent. VK_NUMPAD0: Key = "0 "; Break; Case KeyEvent. VK_NUMPAD1: Key = "1 "; Break; Case KeyEvent. VK_NUMPAD2: Key = "2 "; Break; Case KeyEvent. VK_NUMPAD3: Key = "3 "; Break; Case KeyEvent. VK_NUMPAD4: Key = "4 "; Break; Case KeyEvent. VK_NUMPAD5: Key = "5 "; Break; Case KeyEvent. VK_NUMPAD6: Key = "6 "; Break; Case KeyEvent. VK_NUMPAD7: Key = "7 "; Break; Case KeyEvent. VK_NUMPAD8: Key = "8 "; Break; Case KeyEvent. VK_NUMPAD9: Key = "9 "; Break; Case KeyEvent. VK_MULTIPLY: Key = "× "; Break; Case KeyEvent. VK_DIVIDE: Key = "success "; Break; Case 107: Key = "+ "; Break; Case 109: If (action. getCurrentText (). equals ("0") key = "-"; Else key = "-"; Break; Case KeyEvent. VK_ENTER: Key = "= "; Break; Case 110: Key = "."; Break; Case KeyEvent. VK_BACK_SPACE: Key = "& larr ;"; Break; } If (key. equals ("-1") return true; ButtonMap. get (key). doClick (); } Return true; } }); This. setVisible (true ); This. setResizable (false ); This. setLocationRelativeTo (null ); This. Setdefaclocloseoperation (EXIT_ON_CLOSE ); } Public void batchCreateButton (String [] [] buttonTitle, JPanel, ActionListener listener ){ For (String [] title: buttonTitle ){ If (title. length = 2) panel. add (createButton (title [0], title [1], this )); Else panel. add (createButton (title [0], this )); } } Public JButton createButton (String title, String tipText, ActionListener listener ){ JButton button = createButton (title, this ); Button. setToolTipText (tipText ); Return button; } Public JButton createButton (String title, ActionListener listener ){ JButton button = new JButton (title ); ActionsMap. put (button. hashCode (), title ); ButtonMap. put (title, button ); Button. addActionListener (listener ); Button. setFont (new Font ("Arial", 0, 20 )); Return button; } Public void showMessage (String message ){ JOptionPane. showMessageDialog (null, message ); } @ Override Public void actionreceivmed (ActionEvent e ){ String command = (String) actionsMap. get (e. getSource (). hashCode ()); Action. doAction (command ); } } At the beginning, I used the border layout (BorderLayout) + grid layout (GridLayout) to create an interface. However, I encountered problems such as difficult to control the width of the North-South height and middle filling, finally, I got down and went straight to the absolute layout. In the future, more exercises will be required. Note that when adding a listener to a control, you also need to use HashMap to identify each control and store the commands pointed to by the control. In addition, KeyboardFocusManager is used to add shortcuts to the window. The following is the controls class that handles control events and computing operations. Package me. jerrys. calc; Import java. math. BigDecimal; Public class CalcAction { Private CalcUI UI; Private BigDecimal lastNum = new BigDecimal ("0 "); Private BigDecimal currentNum = new BigDecimal ("0 "); Private String currentText; Private boolean typeClean = false; Private boolean hadCalced = false; Private MODE currentMode = MODE. PLUS; Private enum MODE { PLUS, MINUS, MULTIPLY, DIVIDE } Public static void main (String [] args ){ New CalcAction (); } Public CalcAction (){ This. UI = new CalcUI (this ); } Public void doAction (String command ){ CurrentText = UI. rusultLabel. getText (); Switch (command ){ Case "C ": Clear (); Break; Case "& larr ;": BackSpace (); Break; Case "+ ": SetMode (MODE. PLUS ); Break; Case "-": SetMode (MODE. MINUS ); Break; Case "× ": SetMode (MODE. MULTIPLY ); Break; Case "when ": SetMode (MODE. DIVIDE ); Break; Case "= ": Calc (); Break; Case "+ /-": AddSign (); Break; Default: AddNumber (command ); } } Private void calc (){ If (hadCalced & typeClean) return; CurrentNum = new BigDecimal (currentText ); Try { Switch (currentMode ){ Case PLUS: LastNum = lastNum. add (currentNum ); Break; Case MINUS: LastNum = lastNum. subtract (currentNum ); Break; Case MULTIPLY: LastNum = lastNum. multiply (currentNum ); Break; Case DIVIDE: LastNum = lastNum. divide (currentNum, 16, BigDecimal. ROUND_HALF_DOWN ); Break; } } Catch (Exception e ){ UI. showMessage ("error:" + e. getMessage ()); Return; } String resultText = lastNum. toString (); If (resultText. indexOf (".")> 0) {// removes the extra digits of a decimal number. ResultText = resultText. replaceAll ("0 +? $ ",""); ResultText = resultText. replaceAll ("[.] $ ",""); } SetResultText (resultText ); TypeClean = true; HadCalced = false; } Private void setMode (MODE mode ){ If (! HadCalced &&! TypeClean ){ Calc (); CurrentMode = mode; Return; } LastNum = new BigDecimal (currentText ); CurrentMode = mode; TypeClean = true; HadCalced = true; } Private void addSign (){ If (currentText. equals ("0") | currentText. equals ("") return; If (currentText. startsWith ("-") setResultText (currentText. substring (1 )); Else setResultText ("-" + currentText ); } Private void backSpace (){ If (currentText. equals ("0") | currentText. equals ("") return; If (currentText. length () = 1 ){ SetResultText ("0 "); Return; } SetResultText (currentText. substring (0, currentText. length ()-1 )); } Private void addNumber (String num ){ String resultText = currentText; If (typeClean = true ){ ResultText = "0 "; TypeClean = false; } If (num. equals (".") & currentText. lastIndexOf (".")! =-1) return; If (resultText. equals ("0") | resultText. equals ("")) &&! Num. equals (".")) ResultText = ""; ResultText = resultText + num; SetResultText (resultText ); } Private void clear (){ CurrentNum = new BigDecimal ("0 "); LastNum = new BigDecimal ("0 "); TypeClean = false; CurrentMode = MODE. PLUS; SetResultText ("0 "); } Public String getCurrentText (){ Return currentText; } Private void setResultText (String text ){ UI. rusultLabel. setText (text ); } } |