每当我在计算器上点击1时,它应该执行t1.setText("1");但它只会在textfield1,textfield2,textfield3上有文本的情况下才会这样做如果没有,它会产生错误,下面是我的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
GridLayout layout = new GridLayout(4, 2);
JLabel l1 = new JLabel("Number 1:");
JLabel l2 = new JLabel("Number 2:");
JLabel l3 = new JLabel("Answer:");
JTextField t1 = new JTextField(30);
JTextField t2 = new JTextField(30);
JTextField t3 = new JTextField(30);
JPanel botleft = new JPanel();
JPanel botright = new JPanel();
JButton clear = new JButton("Clear");
JButton n0 = new JButton("0");
JButton n1b = new JButton("1");
JButton n2 = new JButton("2");
JButton n3 = new JButton("3");
JButton n4 = new JButton("4");
JButton n5 = new JButton("5");
JButton n6 = new JButton("6");
JButton n7 = new JButton("7");
JButton n8 = new JButton("8");
JButton n9 = new JButton("9");
JButton add = new JButton("+");
JButton sub = new JButton("-");
JButton mul = new JButton("*");
JButton div = new JButton("/");
JButton equals = new JButton("=");
Float ans;
{
botleft.setLayout(new GridLayout(4,2));
botright.setLayout(new GridLayout(4,2));
botleft.add(n1b);
botleft.add(n2);
botright.add(n3);
botright.add(add);
botleft.add(n4);
botleft.add(n5);
botright.add(n6);
botright.add(sub);
botleft.add(n7);
botleft.add(n8);
botright.add(n9);
botright.add(mul);
botleft.add(n0);
botleft.add(clear);
botright.add(equals);
botright.add(div);
}
public Calculator()
{
super("Calculator");
setSize(300, 300);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(botleft);
add(botright);
setLayout(layout);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
n1b.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String n1 = t1.getText();
String n2 = t2.getText();
Float num1 = Float.parseFloat(n1);
Float num2 = Float.parseFloat(n2);
Object clicked = e.getSource();
if (n1b == clicked)
{
t1.setText("1");
}
else if(add == clicked)
{
t3.setText(String.valueOf(num1+num2));
}
else if(sub == clicked)
{
t3.setText(String.valueOf(num1-num2));
}
else if(mul == clicked)
{
t3.setText(String.valueOf(num1*num2));
}
else
{
if(num2 == 0)
t3.setText("Can't Divide By Zero");
else
t3.setText(String.valueOf(num1/num2));
}
}
}
这是另一个读取它的类:
public class CalcReader
{
public static void main(String[] args)
{
Calculator calc = new Calculator();
calc.setVisible(true);
}
}
在获得ActionListener
中的源对象之前,您正在解析JTextField
t1
中的值。如果这个字段是空的(或者包含一个无效的数字),您将在能够调用t1.setText("1")
之前得到一个NumberFormatException
。先试试:
Object clicked = e.getSource();
if (n1b == clicked) {
t1.setText("1");
} else if // handle all other conditions...
旁白:操作动作的性质(+
, -
等)是足够不同的,每个JButton
有自己的ActionListener
在这里,而不是试图破译什么按钮被点击。