import javax.swing.*;import java.awt.*;/*** 计算器
*@authorpaul
* 2019.11.25 21:43
**/
public classMyCalculator {private String str="";//输入输出框内容
private JTextField text_input;//输出框
private JPanel jp_bottomArea;//按钮区域
private String []addsButtonString={"1","2","3","+","4","5","6","-","7","8","9","*",".","0","求根","/","=","取反","AC"};publicMyCalculator(){//初始化窗体
JFrame frame=new JFrame("计算器");
Container c=frame.getContentPane();
c.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));//设置排布方式为Y轴排列
frame.setLocation(200,300);//设置位置
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
text_input=new JTextField(30);
text_input.setHorizontalAlignment(JTextField.RIGHT);
JPanel jPanel=new JPanel(new GridLayout(1,1,10,10));
jPanel.add(text_input);
c.add(jPanel);
GridBagLayout gridBagLayout=newGridBagLayout();
GridBagConstraints cs=newGridBagConstraints();
jp_bottomArea=newJPanel();
jp_bottomArea.setLayout(gridBagLayout);for(int i=0;i
cs.gridwidth=GridBagConstraints.REMAINDER;
}else if(addsButtonString[i].equals("=")){
cs.gridwidth=2;
}else{
cs.fill=GridBagConstraints.BOTH;
cs.weightx=1.0;
cs.gridwidth=1;
}
JButton btn= newJButton(addsButtonString[i]);
gridBagLayout.setConstraints(btn,cs);
btn.addActionListener(e->{
String command=e.getActionCommand();
setShowTextFiledNew(command);
});
jp_bottomArea.add(btn);
}
c.add(jp_bottomArea);
frame.pack();
}/*** 设置显示内容窗格
*@paramcommand 按钮点击命令
* 如果按下等于,则执行计算
* 如果按下运算符,则格式为 空格+运算符+空格
* 如果按下时数字,则直接拼接
**/
public voidsetShowTextFiledNew(String command){if(command.equals("=")){
str=getResult(str);
}else if(command.equals("+")||command.equals("-")||command.equals("*")||command.equals("/")||command.equals("求根")||command.equals("取反")){
str=str+" "+command+" ";
}else if(command.equals("AC")){
str="";
}else{
str=str+command;
}
text_input.setText(str);
}/*** 计算
*@paramstr 需要计算的字符串
* 根据空格进行分割成字符串数组
* 然后判断是哪种类型的运算符并进行计算
* 通过一个result来存放最终结果
**/
publicString getResult(String str){
Double result=0.0;
String []need_to_do=str.split(" ");for(int i=0;i
result=result+(Double.parseDouble(need_to_do[i-1])+Double.parseDouble(need_to_do[i+1]));break;case "-":
result=result+(Double.parseDouble(need_to_do[i-1])-Double.parseDouble(need_to_do[i+1]));break;case "*":
result=result+(Double.parseDouble(need_to_do[i-1])*Double.parseDouble(need_to_do[i+1]));break;case "/":
result=result+(Double.parseDouble(need_to_do[i-1])/Double.parseDouble(need_to_do[i+1]));break;case "求根":
result=result+(Math.sqrt(Double.parseDouble(need_to_do[i-1])));break;case "取反":
result=result+(-Double.parseDouble(need_to_do[i-1]));break;
}
}return result+"";
}public static voidmain(String[] args) {newMyCalculator();
}
}