我用java做的计算器,请大虾们帮忙优化一下
package Jisuanqi;import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class calculate extends JFrame implements ActionListener
{
private final String [] a= {"7","8","9","C","4","5","6","/","1","2","3","*","0","-","+","="};
private Button b[] = new Button[a.length];
private JTextField ipt;
String ch ="";
String ch1="";
String ch2 ="";
long result = 0;
private int i = 0;
public calculate()
{
super("计算器");
this.setBounds(300,240,250,200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
this.getContentPane().add(panel,"North");
ipt = new JTextField();
ipt.setHorizontalAlignment(JTextField.RIGHT);
panel.add(ipt);
JPanel panel1 = new JPanel(new GridLayout(4,4,3,3));
this.getContentPane().add(panel1);
for(int i = 0;i<a.length;i++)
{
b[i]=new Button(a[i]);
panel1.add(b[i]);
b[i].addActionListener(this);
}
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b[0])
{
ch="7";
ipt.setText(ipt.getText()+ch);
}if(e.getSource()==b[1])
{
ch="8";
ipt.setText(ipt.getText()+ch);
}if(e.getSource()==b[2])
{
ch="9";
ipt.setText(ipt.getText()+ch);
}if(e.getSource()==b[3])
{
ipt.setText("");
}if(e.getSource()==b[4])
{
ch="4";
ipt.setText(ipt.getText()+ch);
}if(e.getSource()==b[5])
{
ch="5";
ipt.setText(ipt.getText()+ch);
}if(e.getSource()==b[6])
{
ch="6";
ipt.setText(ipt.getText()+ch);
}if(e.getSource()==b[7])
{
i=1;
ch1=ipt.getText();
ipt.setText("");
}if(e.getSource()==b[8])
{
ch="1";
ipt.setText(ipt.getText()+ch);
}if(e.getSource()==b[9])
{
ch="2";
ipt.setText(ipt.getText()+ch);
}if(e.getSource()==b[10])
{
ch="3";
ipt.setText(ipt.getText()+ch);
}if(e.getSource()==b[11])
{
i=2;
ch1=ipt.getText();
ipt.setText("");
}if(e.getSource()==b[12])
{
ch="0";
ipt.setText(ipt.getText()+ch);
}if(e.getSource()==b[13])
{
i=3;
ch1=ipt.getText();
ipt.setText("");
}if(e.getSource()==b[14])
{
i=4;
ch1=ipt.getText();
ipt.setText("");
}if(e.getSource()==b[15])
{
switch(i)
{
case 1:chu();break;
case 2:cheng();break;
case 3:jian();break;
case 4:jia();break;
}
}
}
private void chu()
{
if(Integer.parseInt(ipt.getText())==0)
{
ipt.setText("除数不能为零!");
}
result = Integer.parseInt(ch1)/Integer.parseInt(ipt.getText());
ipt.setText(""+result);
}
private void cheng()
{
result = Integer.parseInt(ch1)*Integer.parseInt(ipt.getText());
ipt.setText(""+result);
}
private void jia()
{
result = Integer.parseInt(ch1)+Integer.parseInt(ipt.getText());
ipt.setText(""+result);
}
private void jian()
{
result = Integer.parseInt(ch1)-Integer.parseInt(ipt.getText());
ipt.setText(""+result);
}
public static void main(String args[])
{
new calculate();
}
}