如何使用IntBinaryOperator和Java Swing的Switch Case语句? (简单计算器)

如何使用IntBinaryOperator和Java Swing的Switch Case语句? (简单计算器)

问题描述:

我在使用switch-statement和IntBinaryOperator时遇到了输出问题。我试图用Java构建一个简单的计算器,我发现IntBinaryOperator减少了不必要的样板代码。我希望你能告诉我最好的方法。谢谢。如何使用IntBinaryOperator和Java Swing的Switch Case语句? (简单计算器)

我写的三个类都在下面。

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 

    } 

} 
+0

我不认为我明白的问题到底是什么。 OpButtonsJP使用自己作为ActionListener,而不是CalculatorJFrame,所以应该解释为什么他们从不使用switch语句。又是什么问题? – Lidae

我改变了一点你的代码,基本上我添加了一个表达式的评估器。 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

+0

有趣的方法。它工作得很好。谢谢。 –