使用JFrame的继承方法编写简单的乘法计算器
时间: 2024-02-23 18:01:42 浏览: 57
好的,以下是一个使用 JFrame 继承方法编写的简单乘法计算器示例:
```java
import javax.swing.*;
public class MultiplicationCalculator extends JFrame {
private JLabel num1Label, num2Label, resultLabel;
private JTextField num1Field, num2Field, resultField;
private JButton calculateButton;
public MultiplicationCalculator() {
setTitle("Multiplication Calculator");
setLayout(null);
num1Label = new JLabel("First number:");
num1Label.setBounds(20, 20, 100, 20);
add(num1Label);
num1Field = new JTextField();
num1Field.setBounds(130, 20, 100, 20);
add(num1Field);
num2Label = new JLabel("Second number:");
num2Label.setBounds(20, 50, 100, 20);
add(num2Label);
num2Field = new JTextField();
num2Field.setBounds(130, 50, 100, 20);
add(num2Field);
calculateButton = new JButton("Calculate");
calculateButton.setBounds(90, 80, 100, 20);
calculateButton.addActionListener(e -> calculate());
add(calculateButton);
resultLabel = new JLabel("Result:");
resultLabel.setBounds(20, 110, 100, 20);
add(resultLabel);
resultField = new JTextField();
resultField.setBounds(130, 110, 100, 20);
resultField.setEditable(false);
add(resultField);
setSize(270, 180);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void calculate() {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
int result = num1 * num2;
resultField.setText(Integer.toString(result));
}
public static void main(String[] args) {
new MultiplicationCalculator();
}
}
```
这个程序创建了一个继承 JFrame 类的 MultiplicationCalculator 类。它包含了一个标签、两个文本框、一个按钮和一个文本域,用于显示计算结果。当用户点击“Calculate”按钮时,程序会将两个输入的值相乘并显示结果。希望对您有所帮助!
阅读全文