栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java简单实现计算器

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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);
 }
}

效果图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/129798.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号