赞
踩
代码:
- package ch10;
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
-
- public class Demo02 extends JFrame implements ActionListener {
- JTextArea display;
- JButton[] buttons;
- String[] buttonLabels = {
- "1", "2", "3", "+","C",
- "4", "5", "6", "-","退格",
- "7", "8", "9", "*","1/x",
- "0", "+/-", ".", "/","="};
- String input = "";
- double num1, num2;
- char operator;
-
- public Demo02() {
- setTitle("计算器");
- setSize(400, 400);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setLayout(new BorderLayout());
-
- display = new JTextArea();
- display.setFont(new Font("Serif", Font.PLAIN, 50));
- add(display, BorderLayout.NORTH);
-
- JPanel buttonPanel = new JPanel(new GridLayout(4,5,2,2));
- buttons = new JButton[20];
- for (int i = 0; i < 20; i++) {
- buttons[i] = new JButton(buttonLabels[i]);
- buttons[i].setFont(new Font("Serif", Font.BOLD, 18));
- buttons[i].setForeground(Color.BLUE);
- buttons[i].addActionListener(this);
- buttonPanel.add(buttons[i]);
- }
- buttons[4].setForeground(Color.RED);
- buttons[9].setForeground(Color.RED);
- buttons[19].setForeground(Color.RED);
- add(buttonPanel, BorderLayout.CENTER);
-
-
- }
-
- public void actionPerformed(ActionEvent e) {
- String action = e.getActionCommand();
- if (action.matches("[0-9]")) {
- input += action;
- display.setText(input);
-
- } else if (action.equals("C")) {
- input = input.substring(0, 0);
- display.setText(input);
- }else if (action.equals("退格")) {
- if (input.length() > 0) {
- input = input.substring(0, input.length() - 1);
- display.setText(input);
- }
-
- } else if (action.matches("[+\\-*/]")) {
- num1 = Double.parseDouble(input);
- operator = action.charAt(0);
- input = "";
- } else if (action.equals(".")) {
- if (!input.contains(".")) {
- input += ".";
- display.setText(input);
- }
- } else if (action.equals("=")) {
- num2 = Double.parseDouble(input);
- double result = 0;
- switch (operator) {
- case '+':
- result = num1 + num2;
- break;
- case '-':
- result = num1 - num2;
- break;
- case '*':
- result = num1 * num2;
- break;
- case '/':
- result = num1 / num2;
- break;
- }
- display.setText(String.valueOf(result));
- input = "";
- }
- }
-
- public static void main(String[] args) {
- Demo02 demo=new Demo02();
- demo.setVisible(true);
- }
- }
运行结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。