jframe制作计算器
时间: 2023-09-29 17:05:47 浏览: 77
好的,以下是一个简单的JFrame计算器示例代码,你可以根据自己的需要进行修改:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame implements ActionListener {
private JTextField textField;
private JButton[] buttons;
private String[] buttonText = {"7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", ".", "0", "=", "/"};
private JPanel panel;
public Calculator() {
setTitle("Calculator");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
textField = new JTextField(10);
textField.setEditable(false);
textField.setFont(new Font("Arial", Font.PLAIN, 20));
textField.setHorizontalAlignment(JTextField.RIGHT);
buttons = new JButton[buttonText.length];
for (int i = 0; i < buttonText.length; i++) {
buttons[i] = new JButton(buttonText[i]);
buttons[i].setFont(new Font("Arial", Font.PLAIN, 20));
buttons[i].addActionListener(this);
}
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 5, 5));
for (JButton button : buttons) {
panel.add(button);
}
getContentPane().add(textField, BorderLayout.NORTH);
getContentPane().add(panel, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("=")) {
String expression = textField.getText();
textField.setText(String.valueOf(CalculatorEngine.evaluate(expression)));
} else {
textField.setText(textField.getText() + command);
}
}
public static void main(String[] args) {
new Calculator();
}
}
class CalculatorEngine {
public static double evaluate(String expression) {
//使用JavaScript引擎计算表达式
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
try {
return (double) engine.eval(expression);
} catch (ScriptException e) {
e.printStackTrace();
return Double.NaN;
}
}
}
```
这个计算器使用了 GridLayout 来布局按钮,使用 JavaScript 引擎来计算表达式。
阅读全文