java计算器实现从文本框输出计算结果
时间: 2023-05-12 12:03:58 浏览: 69
可以使用Java的eval()函数来实现计算器的功能,具体代码如下:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField textField;
private JButton[] buttons;
private String[] buttonLabels = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};
public Calculator() {
super("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
textField = new JTextField();
add(textField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
buttons = new JButton[buttonLabels.length];
for (int i = 0; i < buttonLabels.length; i++) {
buttons[i] = new JButton(buttonLabels[i]);
buttons[i].addActionListener(this);
buttonPanel.add(buttons[i]);
}
add(buttonPanel, BorderLayout.CENTER);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("=")) {
String expression = textField.getText();
try {
Object result = eval(expression);
textField.setText(result.toString());
} catch (Exception ex) {
textField.setText("Error");
}
} else {
textField.setText(textField.getText() + command);
}
}
public static Object eval(String expression) throws Exception {
return new javax.script.ScriptEngineManager().getEngineByName("JavaScript").eval(expression);
}
public static void main(String[] args) {
new Calculator();
}
}