java simple calculator

1 Overview

Before the author wrote an article, but also on the calculator, using C ++ and Qt, link here

This time with swing java written (this gap seems a bit big, well qt is too strong).

First on the map:
Here Insert Picture Description

2.UI

The overall layout uses flow layout.

(1) text box

JPanel inside a text box to add a JTextField.

boxField.setLayout(new FlowLayout());
box.setPreferredSize(new Dimension(300, 25));
boxField.add(box);

JTextField dimensioned required setPreferredSize () instead of setSize ().

(2) Key

4 * 4 grid layout key, to add individual button.

buttonsField.setLayout(new GridLayout(4, 4, 20, 20));
buttonsField.setPreferredSize(new Dimension(300, 300));
buttonsField.add(xxx);
//add....

3. mouse events

Mouse events for the button, think about it, click a button, and then inside the text box will have a corresponding reaction, pursuant to add event listeners.

num0.addActionListener(v -> {
    box.setText(box.getText() + "0");
    mainFrame.requestFocus();
});

requestFocus () this line focus back JFrame, because the mouse click button, button gets the focus, it will affect the back of the keyboard monitor.

4. keyboard events

Keyboard and mouse events similar event, you can determine for each key.
Here is the KeyListener registered to JFrame above, the following three methods KeyListener directly inside rewrite:

public void keyPressed(KeyEvent e);
public void keyReleased(KeyEvent e);
public void keyTyped(KeyEvent e);

Basically through

if (e.getKeyCode() == KeyEvent.VK_xxxx)

To judge each key, the only thing to note is that + and *
because the keyboard is not used by the author keypad (embarrassing ....), and + shift + = * need or 8, tried to direct

if (e.getKeyCode() == KeyEvent.VK_PLUS)
if (e.getKeyCode() == KeyEvent.VK_ADD)
if (e.getKeyCode() == KeyEvent.VK_MUTIPLY)

Invalid
it is necessary to determine whether the KeyPressed here pressed the shift, and then to the KeyReleased () when the special judge at 8 =:

else if (e.getKeyCode() == KeyEvent.VK_8)
    box.setText(box.getText() + (shift ? "*" : "8"));
else if(e.getKeyCode() == KeyEvent.VK_EQUALS)
{
    if(shift)
        box.setText(box.getText() + "+");
    else
        setResult();
}

The calculation expression

Evaluate the expression part here told not explained in detail, later in the code.

It is simply to use

GetResult.setExpression();

This static method set expression, then by

GetResult.valid()

To determine whether legal, legitimate, then by

GetResult.result()

String get results.

6. Test

Here Insert Picture Description

Here Insert Picture Description

7. Source

github

Cloud code

Guess you like

Origin www.cnblogs.com/Blueeeeeeee/p/12014434.html