首页javajcomboboxJava Swing - 如何基于来自JComboBox的运算符的两个整数

Java Swing - 如何基于来自JComboBox的运算符的两个整数

我们想知道如何基于来自JComboBox的运算符的两个整数。
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {
  public static void main(String[] args) {
    ScriptEngine engine = new ScriptEngineManager()
        .getEngineByExtension("js");

    String[] ops = { "+", "-", "*", "/" };

    JPanel gui = new JPanel(new BorderLayout(2, 2));
    JPanel labels = new JPanel(new GridLayout(0, 1));
    gui.add(labels, BorderLayout.WEST);
    labels.add(new JLabel("a"));
    labels.add(new JLabel("operand"));
    labels.add(new JLabel("b"));
    labels.add(new JLabel("="));

    JPanel controls = new JPanel(new GridLayout(0, 1));
    gui.add(controls, BorderLayout.CENTER);
    JTextField a = new JTextField(10);
    controls.add(a);
    JComboBox operand = new JComboBox(ops);
    controls.add(operand);
    JTextField b = new JTextField(10);
    controls.add(b);
    JTextField output = new JTextField(10);
    controls.add(output);

    ActionListener al = new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        String expression = a.getText() + operand.getSelectedItem()
            + b.getText();
        try {
          Object result = engine.eval(expression);
          if (result == null) {
            output.setText("Output was 'null'");
          } else {
            output.setText(result.toString());
          }
        } catch (ScriptException se) {
          output.setText(se.getMessage());
        }
      }
    };

    operand.addActionListener(al);
    a.addActionListener(al);
    b.addActionListener(al);

    JOptionPane.showMessageDialog(null, gui);
  }
}