java - 如何将 IntBinaryOperator 与 Java Swing 的 Switch Case 语句一起使用? (简单计算器)

标签 java swing jframe

我在使用 switch 语句和 IntBinaryOperator 时无法获取输出。我正在尝试用 Java 构建一个简单的计算器,我发现 IntBinaryOperator 减少了不必要的样板代码。我希望你能告诉我最好的方法。谢谢。

下面是我编写的三个类。

package gui_calc;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.function.IntBinaryOperator;

public class CalculatorJFrame extends JFrame implements ActionListener {

    static protected JLabel lblOut;
    private JButton btnEq;
    private JButton btnClear;

    public CalculatorJFrame() {
        setTitle("CALCULATOR");
        JPanel container = new JPanel(); //create a JPanel inside the JFrame as a container
        container.setLayout(new BorderLayout());
        //add your components in here
        lblOut = new JLabel("");
        btnEq = new JButton("=");
        btnClear = new JButton("C");
        btnEq.addActionListener(this);
        btnClear.addActionListener(this);
        NumButtonsJP numBtns = new NumButtonsJP(); //create an instance of NumButtonsJP
        OpButtonsJP opBtns = new OpButtonsJP(); //create an instance of OpButtonsJP


        container.add(btnClear, BorderLayout.WEST);
        container.add(btnEq, BorderLayout.EAST);
        container.add(lblOut, BorderLayout.NORTH);
        container.add(numBtns, BorderLayout.CENTER); //add the numBtns JPanel to the container
        container.add(opBtns, BorderLayout.SOUTH); //add the opBtns JPanel to the container
        add(container); //add container to the JFrame
    }

    static protected void updateOutLabel(String suffix) {
        String currLblContent = lblOut.getText().trim(); //get current content of lblOut
        lblOut.setText(currLblContent + suffix); //update the output label on the main container
    }

    static protected void clearOutLabel() {
        lblOut.setText("");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String face = e.getActionCommand().trim();

        switch (face) {
            case "=":
                //do math... get the values... and reset the label with the result
                updateOutLabel("=" + getResultFromQuestion(lblOut.getText()));
                break;
            case "+":
                IntBinaryOperator add = (a,b) -> a + b;

                System.out.println("Your answer is" + (add));
                break;
            case "-":
                IntBinaryOperator substract = (a, b) -> a - b;
                System.out.println("Your answer is" + (substract.applyAsInt(lblOut.getText().charAt(0),lblOut.getText().charAt(1))));
                break;
            case "*":
                IntBinaryOperator multiply = (a, b) -> a * b;
                System.out.println("Your answer is" + (multiply));
                break;
            case "/":
                IntBinaryOperator divide = (a, b) -> a / b;
                System.out.println("Your answer is" + divide);
            case "C":
                clearOutLabel();
                break;
        }

    }

    private String getResultFromQuestion(String text) {
        double resultStr = 10;

        return "" + resultStr;
    }

    public static void main(String[] args) {
        //create instance of calculator and run it
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                CalculatorJFrame calcGUI = new CalculatorJFrame();
                calcGUI.setDefaultCloseOperation(calcGUI.EXIT_ON_CLOSE);
                calcGUI.setSize(300, 300);
                calcGUI.setVisible(true);
            }
        });
    }




  package gui_calc;

    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    import javax.swing.JButton;
    import javax.swing.JPanel;

    public class OpButtonsJP extends JPanel implements ActionListener{

        JButton btnAdd = new JButton("+");
        JButton btnSub = new JButton("-");
        JButton btnMul = new JButton("*");
        JButton btnDiv = new JButton("/");
        JButton [] opsBtns = {btnAdd, btnSub, btnMul, btnDiv};//array of jbuttons

        public OpButtonsJP(){
            setLayout(new GridLayout(1,4));
            for(int i=0; i<opsBtns.length; i++){
                add(opsBtns[i]); //add the button to the JPanel
                opsBtns[i].addActionListener(this); //add the ActionListener to make the button functional
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String face = e.getActionCommand();
            System.out.println(face + " was clicked");
            CalculatorJFrame.updateOutLabel(face);
            //String currLblContent = CalculatorJFrame.lblOut.getText();
            //CalculatorJFrame.lblOut.setText(currLblContent + face); //update the output label on the main container
        }

    }

package gui_calc;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class NumButtonsJP extends JPanel implements ActionListener {

    JButton numButtons[];

    public NumButtonsJP() {
        setLayout(new GridLayout(4, 3));
        numButtons = new JButton[10];
        for (int i = 1; i < 10; i++) {
            //create a JButton with the number on its face and add it to the array of JButtons
            numButtons[i] = new JButton("" + i);
            numButtons[i].addActionListener(this); //make the button trigger the event
            //add the JButton to the JPanel
            add(numButtons[i]);
        }
        JLabel spaceHolder = new JLabel(); //create the spaceHolder as a blank label
        add(spaceHolder); //add the spaceHolder to the JPanel
        numButtons[0] = new JButton("0"); //create the Zero button
        numButtons[0].addActionListener(this);//make the Zero button trigger actioNPerformed
        add(numButtons[0]); //add the Zero button to the JPanel
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        String face = e.getActionCommand();
        System.out.println(face + " was clicked");
        int num = Integer.parseInt(face.trim()); // parse to an int so we can use in math
        CalculatorJFrame.updateOutLabel(face);
        //String currLblContent = CalculatorJFrame.lblOut.getText();
        //CalculatorJFrame.lblOut.setText(currLblContent + face); //update the output label on the main container

    }

}

最佳答案

我稍微改变了你的代码,基本上我添加了一个表达式的求值器。 UI 基本上构建表达式并传递给 getResultFromQuestion() 函数,该函数接受输入,然后尝试解析为数学函数。 您必须正确处理异常,这会破坏您的 BinaryOperators,因为您可以输入两个以上的操作数。

@Override
public void actionPerformed(ActionEvent e) {
    String face = e.getActionCommand().trim();
    switch (face) {
    case "=":
        // do math... get the values... and reset the label with the result
        updateOutLabel("=" + getResultFromQuestion(lblOut.getText()));
        break;
    case "C":
        clearOutLabel();
        break;
    }
}
private String getResultFromQuestion(String text) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    Object result = null;
    try {
        result = engine.eval(text);
    } catch (ScriptException e) {
        //Do something with the exception
    }
    return result.toString();
}

enter image description here

关于java - 如何将 IntBinaryOperator 与 Java Swing 的 Switch Case 语句一起使用? (简单计算器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40517086/

相关文章:

java - 如何使用java + hibernate将值插入SQL Server中的主键?

java - 如何将 JTextField 中的数据传输到 JLabel?

java - 我如何检查是否有东西离开屏幕? - 框架

java - 将多个 JPanel 添加到 JFrame

java - JFrame 踢出我不明白的错误

java - 格式化 .txt 文件中的数据的正确方法是什么? ( java )

java - 使用 Gradle 将 Facebook SDK 添加到 android studio 项目。 Manifest merge failed 错误来了。多个支持库冲突。该怎么办?

java - 暂停 Android 应用程序,直到提供输入

java - 为什么组件的绘制会延迟?

java - 矩形坐标未更新