java语言做图形化计算器使用 Scanner 类将输入的每个 String 类对象转换为int 值。将这两个值相加并在窗口中的 JLabel 对象 output当前不可见中显示结果。我们可以使用 setText方法将计算结果设置给 output 的文本框中注意该方法需要 String 类对象的输入。
以下是Java语言实现的图形化计算器代码示例:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
public class Calculator extends JFrame implements ActionListener {
private JLabel inputLabel1, inputLabel2, outputLabel;
private JTextField inputField1, inputField2;
private JButton addButton;
public Calculator() {
super("Calculator");
// 创建组件
inputLabel1 = new JLabel("Input 1:");
inputLabel2 = new JLabel("Input 2:");
outputLabel = new JLabel("Result:");
inputField1 = new JTextField(10);
inputField2 = new JTextField(10);
addButton = new JButton("Add");
// 设置布局
setLayout(new GridLayout(3, 2));
// 添加组件
add(inputLabel1);
add(inputField1);
add(inputLabel2);
add(inputField2);
add(outputLabel);
add(addButton);
// 注册事件监听器
addButton.addActionListener(this);
// 设置窗口属性
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(300, 150);
setLocationRelativeTo(null);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addButton) {
// 获取输入值
String input1 = inputField1.getText();
String input2 = inputField2.getText();
// 将输入值转换为int类型
int num1 = Integer.parseInt(input1);
int num2 = Integer.parseInt(input2);
// 计算结果
int result = num1 + num2;
// 将结果显示在输出标签中
outputLabel.setText("Result: " + result);
outputLabel.setVisible(true);
}
}
public static void main(String[] args) {
new Calculator();
}
}
运行该程序,将会弹出一个带有两个输入框和一个按钮的窗口。当点击按钮时,程序会将两个输入框中的值相加,并在窗口中显示结果。需要注意的是,输入的值必须为整数,否则会抛出NumberFormatException异常
原文地址: https://www.cveoy.top/t/topic/faIh 著作权归作者所有。请勿转载和采集!