日期:2014-05-20 浏览次数:20814 次
package caofeng; import java.awt.BorderLayout; import java.awt.Container; 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.JTextArea; public class Calculator implements ActionListener{ private String str = ""; private JTextArea jtf; private JFrame frame; private Container contentPane; private String []names={"1","2","3","+","退格", "4","5","6","-","刷新", "7","8","9","*",".", "0","(",")","/","=" }; private JButton []buttons=new JButton[20]; public Calculator(){ //构造方法 frame=new JFrame("Calculator"); //定义一个框架 contentPane=frame.getContentPane(); //获取内容格 JPanel jp1=new JPanel(); //定义一个面板 jtf=new JTextArea("",7,43); jtf.setEditable(false); jp1.add(jtf); JPanel jp2=new JPanel(); jp2.setLayout(new GridLayout(4,5,5,5)); //设置布局管理器 this.fillJP2(jp2); contentPane.add(jp1,BorderLayout.NORTH); contentPane.add(jp2,BorderLayout.SOUTH); frame.setSize(500,300); frame.setVisible(true); } private void fillJP2(JPanel j){ //添加组件 for(int i=0;i<names.length;i++){ buttons[i]=new JButton(names[i]); j.add(buttons[i]); buttons[i].addActionListener(this); } } private boolean isQiTa(String str) { if (str.equals("刷新") || str.equals("退格")) return true; return false; } public void actionPerformed(ActionEvent e){ //事件处理 String strCommand = e.getActionCommand(); if (!isQiTa(strCommand)&&!strCommand.equals("=")) { str += strCommand; jtf.setText(str); } if (strCommand == "退格") { if (str == "") jtf.setText("到头了,你还退什么退啊"); else { if (str.length() == 1){ str =""; jtf.setText(str); } else { str = str.substring(0, str.length() - 1); jtf.setText(str); } } } else if (strCommand == "刷新") { str=""; jtf.setText(str); }else if(strCommand.equals("=")){ str+="="; ///////////////////////////////// float f=new DealwithString().dealwithString(str); //调用 ///////////////////////////////// str+=f; jtf.setText(str); } } public static void main(String args[]){ new Calculator(); } }