0

每当我在计算器上单击 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);
}
}
4

1 回答 1

2

在将源对象放入JTextField t1 . ActionListener如果此字段为空(或包含无效号码),您将NumberFormatException在可以拨打电话之前得到一个t1.setText("1")首先尝试这样做:

Object clicked = e.getSource();
if (n1b == clicked) {
   t1.setText("1");
} else if // handle all other conditions...

另外:操作动作( , 等)的性质+-完全不同的,每个动作JButton都有自己的ActionListener,而不是试图破译点击了哪个按钮。

于 2013-03-13T16:05:36.817 回答