题目:
设计并实现一个类似于windows操作系统附件中自带的计算器的一款简单的计算器,要求界面美观,设计合理;带有常用的菜单并实现其功能;能完成加、减、乘、除等简单的计算,在下面写出其核心代码。
解答:
package Experiment_4;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Clac {
static double num1 = 0, num2 = 0; //定义num1为历史数据,num2为当前数据
static char ch = '+'; //定义ch为当前运算符
static String s = ""; //定义s为展示的数据
static boolean flag = false; //定义flag标志是否刚做完求值运算
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true); //设置JFram外观风格
JFrame frame = new JFrame("clac"); //创建一个JFrame类顶级容器
frame.setSize(400, 600);
frame.setLayout(new GridLayout(2,1));
//获得顶级容器的内容面板contentPane,只有通过它才能加入其他组件
//它属于中间容器JRootPane的一部分
Container contentPane = frame.getContentPane();
JPanel panel1 = new JPanel();
panel1.setSize(400, 120);
panel1.setLayout(new GridLayout(1,1)); //设置布局
final JLabel label = new JLabel("0",SwingConstants.CENTER); //创建原子组件Label
label.setSize(400, 120);
//将原子组件添加到中间容器上
panel1.add(label);
panel1.setBorder(BorderFactory.createLineBorder(Color.black, 2));
contentPane.add(panel1, BorderLayout.PAGE_START);
//frame.add(panel1, BorderLayout.PAGE_START);
JPanel panel2 = new JPanel(); //创建一个JPanel类的中间容器panel
panel2.setBorder(BorderFactory.createLineBorder(Color.black, 3)); //设置边框
panel2.setLayout(new GridLayout(6, 4)); //设置布局
panel2.setSize(400, 480);
//对历史结果进行百分号运算
JButton button1 = new JButton("%");
button1.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {num1 *= 0.01; label.setText(Double.toString(num1));}});
panel2.add(button1);
//清除当前数据
JButton button2 = new JButton("CE");
button2.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {s = ""; num2 = 0; label.setText("0");}});
panel2.add(button2);
//清除当前数据和历史数据