Java语言写两个int相加并在窗口中的 JLabel 对象 output当前不可见中显示结果。我们可以使用 setText方法将计算结果设置给 output 的文本框中注意该方法需要 String 类对象的输入。
下面是示例代码:
import javax.swing.JFrame;
import javax.swing.JLabel;
public class AddTwoIntegers {
public static void main(String[] args) {
// 创建 JFrame 对象
JFrame frame = new JFrame("Add Two Integers");
// 创建 JLabel 对象并设置位置和大小
JLabel output = new JLabel();
output.setBounds(100, 50, 200, 30);
// 定义两个整数并计算它们的和
int num1 = 10;
int num2 = 20;
int sum = num1 + num2;
// 将计算结果设置给 output 的文本框中
output.setText("Sum of " + num1 + " and " + num2 + " is " + sum);
// 将 JLabel 对象添加到 JFrame 中
frame.add(output);
// 设置 JFrame 的大小和可见性
frame.setSize(400, 150);
frame.setLayout(null);
frame.setVisible(true);
}
}
当运行该程序时,将在窗口中显示如下文本:
Sum of 10 and 20 is 30
``
原文地址: https://www.cveoy.top/t/topic/faHS 著作权归作者所有。请勿转载和采集!