[java]代码库
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* 精简java计算器
*
*/
public class Calculator implements ActionListener {
private JFrame frame;
private JButton[] bus;
private JTextField jtx;
private JButton bu;
private char[] strs;
private String d_one = "";
private String operator;
public static void main(String[] args) {
new Calculator();
}
/* 利用构造进行实例化 */
public Calculator() {
frame = new JFrame("计算器");
jtx = new JTextField(14);
bus = new JButton[16];
strs = "789/456*123-0.+=".toCharArray();
for (int i = 0; i < 16; i++) {
bus[i] = new JButton(strs[i] + "");
bus[i].addActionListener(this);
}
bu = new JButton("C");
bu.addActionListener(this);
init();
}
/* GUI 初始化 */
public void init() {
JPanel jp1 = new JPanel();
jp1.add(jtx);
jp1.add(bu);
frame.add(jp1, BorderLayout.NORTH);
JPanel jp2 = new JPanel();
jp2.setLayout(new GridLayout(4, 4));
for (int i = 0; i < 16; i++) {
jp2.add(bus[i]);
}
frame.add(jp2, BorderLayout.CENTER);
frame.pack();
frame.setLocation(500, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/* 事件的处理 */
public void actionPerformed(ActionEvent arg0) {
/* 获取输入字符 */
String conn = arg0.getActionCommand();
/* 清除计算器内容 */
if ("C".equals(conn)) {
d_one = "";
operator = "";
jtx.setText("");
return;
}
/* 暂未实现该功能 */
if (".".equals(conn)) {
return;
}
/* 记录运算符,保存运算数字 */
if (("+-*/".indexOf(conn)) != -1) {
if ("".equals(d_one) && "".equals(jtx.getText()))
return;
d_one = jtx.getText();
operator = conn;
jtx.setText("");
return;
}
/* 计算结果 */
if ("=".equals(conn)) {
if ("".equals(d_one) && "".equals(jtx.getText()))
return;
double db = 0;
if ("+".equals(operator)) {
db = Double.parseDouble(d_one)
+ Double.parseDouble(jtx.getText());
jtx.setText(db + "");
}
if ("-".equals(operator)) {
db = Double.parseDouble(d_one)
- Double.parseDouble(jtx.getText());
jtx.setText(db + "");
}
if ("*".equals(operator)) {
db = Double.parseDouble(d_one)
* Double.parseDouble(jtx.getText());
jtx.setText(db + "");
}
if ("/".equals(operator)) {
db = Double.parseDouble(d_one)
/ Double.parseDouble(jtx.getText());
jtx.setText(db + "");
}
d_one = db + "";
return;
}
// 界面显示
jtx.setText(jtx.getText() + conn);
}
}
[代码运行效果截图]