1 overview

Java AWT+Swing implementation of a simple calculator, functions as follows:

  • Support addition, subtraction, multiplication and division
  • Support decimal arithmetic
  • Keyboard monitor
  • The mouse to monitor

2 Effect demonstration

3 Some details

3.1 operation

The operation uses an ExpressionHandle static class to evaluate the value of the string expression.

In fact, the operation is not difficult, just the basic operators and operands on and off the stack operation, I will not go into details.

3.2 Base64

Icon is Base64 processing, because there is only one image resource, and the use of pictures is more likely to appear path problems, the use of Java’s own Base64.Decoder processing, decode after the generation of byte array and as the parameters of ImageIcon, you can correctly display the picture.

3.3 the font

The font is Microsoft YaHei font, bold by default, the font size is 17, and SetFont is set by reflection access.

3.4 Mouse monitoring

The core is the MouseListner, which sets the background color for entry and exit when mouseEntered/mouseExited, and the response event when MouseLicked. The equals sign, backspace, and ESC are specified, and the other characters are added directly to the corresponding input field.

3.5 Keyboard monitoring

The core is keyListner, keyPressed to set the response event, and to specify the return, backspace, and equal sign. You also need to pay attention to key combinations. For example, Shift+8 represents a multiplier sign, and you need to use keyEvent.isShiftDown to determine if Shift is pressed. At the same time, set the corresponding key background color. Set the key release event in keyReleased, here is the setting background, originally intended to set a key, but maybe because the keyboard event response is not sensitive, when the key is too fast will appear the illusion of the key is “continuously pressed”, so all the keys are responded to.

3.6 Limit input characters

Using JTextField. SetDocument () and PlainDocument, when the input is illegal to prompt, and ignore the corresponding input, the core is insertString().

4 source

  • Github
  • Yards cloud