java简单实现计算器
时间:2021-11-08 09:45:11|栏目:JAVA代码|点击: 次
本文实例为大家分享了java简单实现计算器的具体代码,供大家参考,具体内容如下
public class Calculator {
static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
private static void CreateFrame() {
JFrame f = new JFrame("计算器");
f.setSize(600, 500);
f.setVisible(true);
f.setLayout(new BorderLayout());
f.setLayout(new GridLayout(6, 3));
f.setLocation(300, 150);
JTextArea text = new JTextArea(20, 0);
f.add(text, BorderLayout.NORTH);
JButton but1 = new JButton("CE");
f.add(but1, BorderLayout.PAGE_END);
String a[] = { "=", "7", "8", "9", "4", "5", "6", "1", "2", "3", "0", "+", "-", "*", "/", "." };
JButton btn[] = new JButton[a.length];
for (int i = 0; i < a.length; i++) {
btn[i] = new JButton(a[i]);
f.add(btn[i]);
}
// 功能实现
for (int i = 0; i < a.length; i++) {
// 如果不是等于号
if (i != 0) {
int j = i;
btn[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = btn[j].getText();// 获取文本框内容
text.append(s);
}
});
} else {
// 如果点击等于号
btn[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// 获取文本框内容
String gongshi = text.getText();
// 计算获取的文本框中的内容
String jieguo = jse.eval(gongshi).toString();
text.setText("=");
text.setText(jieguo);
} catch (Exception t) {
text.setText("");
}
}
});
// CE按钮
but1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == but1) {
text.setText("");
}
}
});
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(Calculator::CreateFrame);
}
}
效果图:

栏 目:JAVA代码
下一篇:Spring Cloud Alibaba 使用 Feign+Sentinel 完成熔断的示例
本文标题:java简单实现计算器
本文地址:http://www.codeinn.net/misctech/182858.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




