简单的计算器-Java-可视化

本文介绍了一个使用Java实现的简易计算器程序。该程序包含基本算术运算功能,如加、减、乘、除等,并通过图形界面进行操作。代码展示了如何创建按钮响应事件及执行计算逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 package Works_JavaLesson;

import java.awt.*;
import java.awt.event.*;

public class SimpleCalculator {

 /**
  * @param simple calculator
  * @author CHENJIAN
  */
 public static void main(String[] args) {
  SimpleCalculatorFrame frame = new SimpleCalculatorFrame();
  frame.setVisible(true);
  frame.addWindowListener(
   new WindowAdapter(){
    public void windowClosing(WindowEvent event){
     System.exit(0);
    }
   });
 }

}

class SimpleCalculatorFrame extends Frame{
 public SimpleCalculatorFrame(){
  setTitle("---  Simple Calculator  ---");
  setLocation(300, 200);
  setLayout(new BorderLayout());
  
  SimpleCalculatorPanel panel = new SimpleCalculatorPanel();
  add(panel);
  pack();
 }
}

class SimpleCalculatorPanel extends Panel{
 public SimpleCalculatorPanel(){
  setLayout(new BorderLayout());
  panel_A = new Panel();
  panel_B = new Panel();
  lastCommand = "=";
  result = 0;
  
  textfield = new TextField(30);
  textfield.setBackground(Color.WHITE);
  panel_A.add(textfield, BorderLayout.NORTH);
  add(panel_A);
  
  panel_B.setLayout(new GridLayout(2, 3, 3, 3));
  ActionListener command = new CommandAction();
  
  makeButton("*", command);
  makeButton("-", command);
  makeButton("%", command);
  makeButton("+", command);
  makeButton("/", command);
  makeButton("=", command); 
  add(panel_B, BorderLayout.SOUTH);
 }
 public void makeButton(String name, ActionListener listener){
  Button btn = new Button(name);
  btn.addActionListener(listener);
  panel_B.add(btn);
 }
 private class CommandAction implements ActionListener{
  public void actionPerformed(ActionEvent event){
   String input = event.getActionCommand();
   
   if(lastCommand.equals("=")){
    result = Double.parseDouble(textfield.getText());
   }
   else if(lastCommand.equals("*")){
    result *= Double.parseDouble(textfield.getText());
   }
   else if(lastCommand.equals("/")){
    result /= Double.parseDouble(textfield.getText());
   }
   else if(lastCommand.equals("+")){
    result += Double.parseDouble(textfield.getText());
   }
   else if(lastCommand.equals("-")){
    result -= Double.parseDouble(textfield.getText());
   }
   else if(lastCommand.equals("%")){
    result %= Double.parseDouble(textfield.getText());
   }
   lastCommand = input;
   textfield.setText(String.valueOf(result));
  }
 }
 
 private Panel panel_A;
 private Panel panel_B;
 private double result;
 private String lastCommand;
 private TextField textfield;
}

 

 

2009-05-28   09:51:22

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值