我做了一个简单的计算器
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
GridLayout layout = new GridLayout(5, 1);
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);
JButton add = new JButton("+");
JButton sub = new JButton("-");
JButton mul = new JButton("*");
JButton div= new JButton("/");
Float ans;
public Calculator()
{
super("Calculator");
setSize(250, 200);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(add);
add(sub);
add(mul);
add(div);
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));
}
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 UseMyFrame
{
public static void main(String[] args)
{
Calculator calc = new Calculator();
calc.setVisible(true);
}
}
我的问题是我想添加另一个功能并放置 9 个按钮 1-9,按下时会将它们各自的数字放在文本字段上,但我不知道如何将它们设置为出现在文本字段中,我首先要设置。 text 但我意识到按钮如何知道将其编号放在哪里,因为如果我确实 set.text 我需要将它放在 textfield1 或 textfield 2 上。我想让数字首先出现在 textfield1 中,然后在 textfield2 上(如果已经有) textfield1 上的数字