Learning notes for Java simple calculator

Source: Internet
Author: User

In order to practice, I took the time to make this simple calculator ". Let's talk about the problems encountered during the production process.

At the time of creation, the layout of the swing component may be exhausted. I am still familiar with the previous visual component layout method of "What you see is what you get". The following is the UI class used to draw the UI.

The code is as follows: Copy code

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 );
 }
}

We also encountered a problem here. At the beginning, we used the double type to store numerical values. The accuracy of addition, subtraction, multiplication, division, and calculation may be inaccurate, resulting in unexpected results. For example, 10-9.88 would get 0.11999999999999922. To solve this problem, JDK provides the BigDecimal package for precise computing. For details, see.

(Time is tight, not perfect, do not spray)

 

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.