“计算器”能运行,但不能计算结果(诸位大虾帮忙指点下)
import java.awt.*;import java.awt.event.*;
import javax.swing.*;
class MyCounter extends JFrame implements ActionListener
{
private JTextField text;
private JButton[] buttons;
private int symbol; // symbol表示要进行的运算
private int f; // f为点击符号前读入的数
private int l; // l为点击符号后读入的数
private int p; // p为当前读入的数字
private boolean flg; // flg表示是否已经输入符号
private boolean point; // 是否已经输入点
private double result; // result为计算结果
public MyCounter()
{
super("计算器");
this.setSize(200,300);
this.setLocation(400,300);
flg = false;
point = false;
text = new JTextField("0");
text.setBackground(Color.cyan);
text.setHorizontalAlignment(JTextField.RIGHT); // 右对齐显示
text.setEditable(false); //文本框不可编辑
this.add(text,"North");
JPanel p1 = new JPanel(new GridLayout(4,4));
buttons = new JButton[17];
buttons[0] = new JButton("7");
buttons[1] = new JButton("8");
buttons[2] = new JButton("9");
buttons[3] = new JButton("+");
buttons[4] = new JButton("4");
buttons[5] = new JButton("5");
buttons[6] = new JButton("6");
buttons[7] = new JButton("-");
buttons[8] = new JButton("1");
buttons[9] = new JButton("2");
buttons[10] = new JButton("3");
buttons[11] = new JButton("*");
buttons[12] = new JButton("0");
buttons[13] = new JButton(".");
buttons[14] = new JButton("=");
buttons[15] = new JButton("/");
for(int i=0;i<16;i++)
{
p1.add(buttons[i]);
buttons[i].addActionListener(this);
}
this.add(p1,"Center");
JPanel p2 = new JPanel();
buttons[16] = new JButton("清除");
buttons[16].addActionListener(this);
buttons[16].setBackground(Color.green);
p2.add(buttons[16]);
this.add(p2,"South");
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
// 置零
if(e.getSource()==buttons[16])
{
text.setText("0");
}
// 读入数字并显示在文本框上
if(e.getSource()==buttons[0]||e.getSource()==buttons[1]||e.getSource()==buttons[2]
||e.getSource()==buttons[4]||e.getSource()==buttons[5]||e.getSource()==buttons[6]
||e.getSource()==buttons[8]||e.getSource()==buttons[9]||e.getSource()==buttons[10]
||e.getSource()==buttons[12])
{
p = Integer.parseInt(text.getText() + e.getActionCommand());
text.setText(String.valueOf(p));
if(flg)
{
l = p;
}
}
/*if(e.getSource()==buttons[13])
{
if(point)
{
}
}*/
// 读入符号
if(e.getSource()==buttons[3]||e.getSource()==buttons[7]||
e.getSource()==buttons[11]||e.getSource()==buttons[15])
{
f = Integer.parseInt(text.getText());
//设置符号
if(e.getSource()==buttons[3])
symbol = 1;
if(e.getSource()==buttons[7])
symbol = 2;
if(e.getSource()==buttons[11])
symbol = 3;
if(e.getSource()==buttons[15])
symbol = 4;
flg = true;
//text.setText(e.getActionCommand());
text.setText(" ");
}
// 判断是否要计算结果
if(e.getSource()==buttons[14])
{
switch(symbol)
{
case 1:
result = f+l;
break;
case 2:
result = f-l;
break;
case 3:
result = f*l;
break;
case 4:
result = f/l;
break;
}
text.setText(String.valueOf(result));
}
}
public static void main(String[] args)
{
new MyCounter();
}
}