How do I get the buttons on my calculator to actua

2019-09-22 04:32发布

I wanted to make a small calculator project for fun to test out my new GUI knowledge with Java Swing API. I created the GUI, but there's a crucial part missing: The math! My Question is, how do I add functionality to each of these buttons? In simpler terms: How do I make the buttons add something to the text box(2+2) when the user clicks the buttons, and then have the system actually add the numbers together and display them for the user?

Here's the code:

package calculatorPack;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.UIManager;


public class basicCalculatorDesign {


    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } 
            catch (Exception e) {
            }
        basicCalculatorDesign calc = new basicCalculatorDesign();
        calc.start();
    }


    JTextArea input = new JTextArea();
    String[] operators;
    int[] numbers;

    public void start() {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        JButton one = new JButton("1");
        JButton two = new JButton("2");
        JButton three = new JButton("3");
        JButton four = new JButton("4");
        JButton five = new JButton("5");
        JButton six = new JButton("6");
        JButton seven = new JButton("7");
        JButton eight = new JButton("8");
        JButton nine = new JButton("9");
        JButton zero = new JButton("0");
        JButton plus = new JButton("+");
        JButton minus = new JButton("-");
        JButton divide = new JButton("/");
        JButton multiply = new JButton("*");
        JButton sqrt = new JButton("SqRt");
        JButton percentage = new JButton("%");
        JButton equals = new JButton("=");

        // work on this


        JLabel label = new JLabel("Basic Calculator");
        frame.getContentPane().add(BorderLayout.NORTH, label);

        frame.getContentPane().add(BorderLayout.SOUTH, input);

        panel.setBackground(Color.BLUE);
        panel.setLayout(new GridBagLayout());

        JPanel panel2 = new JPanel();
        panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
        panel2.setBackground(Color.RED);
        frame.getContentPane().add(BorderLayout.EAST, panel2);

        frame.getContentPane().add(BorderLayout.CENTER, panel);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setSize(210, 260);


        GridBagConstraints right = new GridBagConstraints();
        right.anchor = GridBagConstraints.WEST;
        GridBagConstraints left = new GridBagConstraints();
        left.anchor = GridBagConstraints.EAST;
        GridBagConstraints middle = new GridBagConstraints();
        middle.anchor = GridBagConstraints.CENTER;
        right.gridwidth = GridBagConstraints.REMAINDER;
        right.fill = GridBagConstraints.HORIZONTAL;

        // add buttons
        panel.add(one, left);
        panel.add(two, middle);
        panel.add(three, right);
        panel.add(four, left);
        panel.add(five, middle);
        panel.add(six, right);
        panel.add(seven, left);
        panel.add(eight, middle);
        panel.add(nine, right);
        panel.add(zero, right);

        panel2.add(equals);
        panel2.add(plus);
        panel2.add(minus);
        panel2.add(divide);
        panel2.add(multiply);
        panel2.add(sqrt);
        panel2.add(percentage);

        //integrate buttons 
        one.addActionListener(new ButtonListener());
        two.addActionListener(new ButtonListener());
        three.addActionListener(new ButtonListener());
        four.addActionListener(new ButtonListener());
        five.addActionListener(new ButtonListener());
        six.addActionListener(new ButtonListener());
        seven.addActionListener(new ButtonListener());
        eight.addActionListener(new ButtonListener());
        nine.addActionListener(new ButtonListener());
        zero.addActionListener(new ButtonListener());

        equals.addActionListener(new OperatorListener());
        }


    class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JButton source = (JButton)e.getSource();
            input.replaceSelection(source.getActionCommand());  

        }
    }

    class OperatorListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JButton source2 = (JButton)e.getSource();
            input.replaceSelection(source2.getActionCommand());

        }
    }

    // I need THIS to do math. 
    class EqualsListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {


        }
    }
}

2条回答
Viruses.
2楼-- · 2019-09-22 04:42

They way I understand your code, you are creating a text area with string which happen to look like formula ("1+1"). I'm not sure if that code even works, because the way I see it, you are just replacing one number with another. This is only text anyway so it doesn't matter.

If you want to do math, you must change your code to make a real number out of a text. Since you are converting only a single digit, that's easy.

You must know which is the first number and which is the second number. Then, when the user presses the '=' button you can execute it.

So it's something like this:

setVal1(-1);
setVal2(-1);
setOperation(null);

in your button listener do somethign like this:

int val = Integer.parseInt(buttontext);
if(getVal1() == -1)
   setVal1val);
else
   setVal2(val);

in your operator listener do something like this:

setOperation(OperationFromButton);

In you equal listener do something like this:

if(getVal1() == -1 || getVal2() == -1 || getOperation() == null)
    return error or nothing;

if(operation == "+")
   result = getVal1()+getVal2();
else if(operation == "-")
   result = getVal1()-getVal2();
...
查看更多
闹够了就滚
3楼-- · 2019-09-22 05:02

It looks like you want to evaluate an arithmetic expression. Some options:

  • Use an available ScriptEngine, shown here and here.

  • Write a recursive descent parser, illustrated here.

  • Evaluate the expression as the user types in the text area by using a DocumentListener, discussed here.

查看更多
登录 后发表回答