使用 AWT 添加 2 个整数

Adding 2 Integers using AWT

我正在尝试使用这些代码创建 Java AWT 程序:

import javax.swing.*;
import java.awt.*;

public class Exer1 extends JFrame {

    public Exer1(){

        super ("Addition");
        JLabel add1 = new JLabel("Enter 1st Integer: ");
        JTextField jtf1 = new JTextField(10);
        JLabel add2 = new JLabel("Enter 2nd Integer: ");
        JTextField jtf2 = new JTextField(10);
        JButton calculate = new JButton("Calculate");
        FlowLayout flo = new FlowLayout();
        setLayout(flo);
        add(add1);
        add(jtf1);
        add(add2);
        add(jtf2);
        add(calculate);
        setSize(200,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);

    }

    public static void main(String[] a){
        Exer1 ex1 = new Exer1();
    }

}

我的问题是如何使用 JTextField 添加这 2 个整数。有人能帮我吗?太感谢了。 :)

通常,您应该为按钮上的点击事件创建一个事件侦听器:Lesson: Writing Event Listeners。在该处理程序中,您将获取两个文本字段的内容,将它们转换为整数:

Integer i1 = Integer.valueOf(jtf1.getText());

然后您可以将这两个整数相加并将它们显示在另一个控件中或对它们执行任何其他操作。

How to Use Buttons, Check Boxes, and Radio Buttons 开始,然后 How to Write an Action Listeners

这将为您提供您需要能够在用户按下按钮时判断的信息。

JTextField#getText 然后是 return 的 String。然后问题就变成了将 String 转换为 int 的问题,如果你花时间,有数以千计的示例演示如何实现

一旦你玩弄了将 String 转换为 int 的奇怪之处,你可以看看 How to Use Spinners and How to Use Formatted Text Fields,它对输入的值执行自己的验证

您需要在 JButton 上使用 ActionListener

然后你需要从 JTextField 中得到 int,然后像下面那样对它们求和:

calculate.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                int i1 = Integer.valueOf(jtf1.getText());
                int i2 = Integer.valueOf(jtf2.getText());
                System.out.println("sum=" + (i1 + i2));
            } catch (Exception e1){
                e1.printStackTrace();
            }
        }
    });