package test;
import java.awt.Color;
import java.awt.Font;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator {
public Calculator() {
}
//创建五个面板
JPanel panel3=new JPanel(); //上半部分
JPanel buttonPane=new JPanel(); //存按钮
JLabel expLabel,resultLabel;
String exp="",result="";
String[] buttons= {
"1","2","3","+","Del","4","5","6","-","C","7","8","9","*","01",".","0","=","/","02"
};
public void initButton() {
buttonPane.setLayout(new GridLayout(4,5));
for(String s:buttons) {
JButton button=new JButton(s);
buttonPane.add(button);
button.setFont(new Font("宋体",Font.BOLD,18));
button.setForeground(Color.GREEN);
button.addActionListener(new MyActionListener());
}
}
private class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String c=e.getActionCommand();
for(int i=0;i<10;i++)
{
if(c.equals(i+"")) {
exp+=c;
expLabel.setText(exp);
return;
}
}
switch(c) {
case "+":
exp +="+";
break;
case "-":
exp +="-";
break;
case "*":
exp +="*";
break;
case "/":
exp +="/";
break;
case "Del":
exp=exp.substring(0,exp.length()-1);
break;
case "c":
clear();
break;
case "=":
default:
break;
}
expLabel.setText(exp);
if(!result.equals("")) {
resultLabel.setText(result);
}
}
}
public void clear() {
exp="";
result="";
resultLabel.setText(result);
}
public void compute() {
String[] arr=exp.split(" ");
Double num1=Double.parseDouble(arr[0]);
}
public void initLabel() {
expLabel=new JLabel();
resultLabel=new JLabel();
}
public void showUI() {
JFrame window=new JFrame("计算器");
window.setSize(400,500);
window.setLayout(new GridLayout(2,1));
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initButton();
initLabel();
panel3.setLayout(new GridLayout(2,1));
panel3.add(expLabel);
panel3.add(resultLabel);
window.add(panel3);
window.add(buttonPane);
window.setVisible(true);
}
public static void main(String[] args) {
Calculator Cal=new Calculator();
Cal.showUI();
}
}