我创建了一个工作正常的文本计算器;但我希望计算器打印出用户输入的内容,因为他或她在我的文本字段t4中键入了它。我知道我必须使用ActionListener并且已经查找了如何使用它,但我仍然无法让它正常工作。我已经尝试创建按钮1-9并向其添加ActionListeners以尝试实时打印出来,我尝试在代码的“public void actionPerformed(ActionEvent e)”部分添加不同的字符串和.getText,但我仍然无法让它工作。 `
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
GridLayout layout = new GridLayout(7, 1);
JLabel l1 = new JLabel("Number 1:");
JLabel l2 = new JLabel("Number 2:");
JLabel l3 = new JLabel("Answer:");
JLabel l4 = new JLabel("Your input:");
JTextField t1 = new JTextField(30);
JTextField t2 = new JTextField(30);
JTextField t3 = new JTextField(30);
JTextField t4 = new JTextField(30);
JButton add = new JButton("+");
JButton sub = new JButton("-");
JButton mul = new JButton("*");
JButton div= new JButton("/");
JButton one = new JButton("1");
Float ans;
public Calculator()
{
super("Calculator");
setSize(250, 200);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(l4);
add(t4);
add(add);
add(sub);
add(mul);
add(div);
add(one);
setLayout(layout);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.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(add == clicked)
{
t3.setText(String.valueOf(num1+num2));
t4.setText(String.valueOf(num1 + "+" + num2 + "=" + (num1+num2)));
}
else if(sub == clicked)
{
t3.setText(String.valueOf(num1-num2));
t4.setText(String.valueOf(num1 + "-" + num2 + "=" + (num1-num2)));
}
else if(mul == clicked)
{
t3.setText(String.valueOf(num1*num2));
t4.setText(String.valueOf(num1 + "*" + num2 + "=" + (num1*num2)));
}
else
{
if(num2 == 0)
t3.setText("Can't Divide By Zero");
else
t3.setText(String.valueOf(num1/num2));
t4.setText(String.valueOf(num1 + "/" + num2 + "=" + (num1/num2)));
}
}
}
public class UseMyFrame
{
public static void main(String[] args)
{
Calculator calc = new Calculator();
calc.setVisible(true);
}
}
`.