关闭

java实现的计算器

828人阅读 评论(0) 收藏 举报
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;

public class ButtonArray {
	public static void main(String[] args) {
		ButtonArrayWin win = new ButtonArrayWin();
	}
}

class ButtonArrayWin extends JFrame implements ActionListener {
	JTextField textField;
	JButton[][] buttons;
	String number = "";
	String operate;
	Double num;
	Boolean flag = true;// 可以输入第一个数
	Boolean flag1 = true;// 可以连续输入
	Double result = 0.0;

	public ButtonArrayWin() {
		super();
		BorderLayout borderLayout = (BorderLayout) getContentPane().getLayout();
		borderLayout.setHgap(20);
		borderLayout.setVgap(20);
		setTitle("按钮数组实现计算器界面");
		setBounds(100, 100, 290, 282);
		setVisible(true);
		validate();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		textField = new JTextField();
		textField.setHorizontalAlignment(SwingConstants.TRAILING);
		textField.setPreferredSize(new Dimension(12, 50));
		getContentPane().add(textField, BorderLayout.NORTH);
		textField.setColumns(10);
		final GridLayout gridLayout = new GridLayout(4, 0);
		gridLayout.setHgap(5);
		gridLayout.setVgap(5);
		JPanel panel = new JPanel();
		panel.setLayout(gridLayout);
		getContentPane().add(panel, BorderLayout.CENTER);
		String[][] names = { { "1", "2", "3", "+" }, { "4", "5", "6", "-" },
				{ "7", "8", "9", "*" }, { ".", "0", "=", "/" } };
		buttons = new JButton[4][4];
		for (int row = 0; row < names.length; row++)
			for (int col = 0; col < names.length; col++) {
				buttons[row][col] = new JButton(names[row][col]);
				buttons[row][col].addActionListener(this);
				panel.add(buttons[row][col]);
			}
	}

	public void actionPerformed(ActionEvent e) {
		JButton button = (JButton) e.getSource();
		if ((button != buttons[0][3]) && (button != buttons[1][3])
				&& (button != buttons[2][3]) && (button != buttons[3][2])
				&& (button != buttons[3][3])) { // button 为数字按钮 输入数字
			if (flag1 == true) {
				number = textField.getText() + button.getText();
				textField.setText(number);
			} else {
				textField.setText("");
				number = textField.getText() + button.getText();
				textField.setText(number);
				flag1 = true;
			}
			num = Double.parseDouble(number);
			if (flag == true)
				result = num; // 输入的是第一个数
			else {
				if (operate.equals("+"))
					result = result + num;
				if (operate.equals("-"))
					result = result - num;
				if (operate.equals("*"))
					result = result * num;
				if (operate.equals("/"))
					result = result / num;
			}
		} else { // button为运算符按钮 计算 
			operate = button.getText();
			if (operate.equals("=")) {
				flag1 = false;
				flag = true;
			}

			else {
				flag1 = false; // 要清空了 再输入第二个数
				flag = false; // 可以运算了
			}
			textField.setText(String.valueOf(result));// 按下操作符 就要输出一次结果
		}
	}

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:44986次
    • 积分:709
    • 等级:
    • 排名:千里之外
    • 原创:22篇
    • 转载:4篇
    • 译文:0篇
    • 评论:5条
    文章分类