使用actionPerformed(ActionEvent e)方法编写简答乘法计算器
时间: 2024-02-23 07:01:52 浏览: 31
好的,以下是使用 `actionPerformed(ActionEvent e)` 方法编写简单乘法计算器的 Java 代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MultiplicationCalculator implements ActionListener {
private JFrame frame;
private JLabel num1Label, num2Label, resultLabel;
private JTextField num1Field, num2Field, resultField;
private JButton calculateButton;
public MultiplicationCalculator() {
frame = new JFrame("Multiplication Calculator");
frame.setLayout(new FlowLayout());
num1Label = new JLabel("First number:");
frame.add(num1Label);
num1Field = new JTextField(10);
frame.add(num1Field);
num2Label = new JLabel("Second number:");
frame.add(num2Label);
num2Field = new JTextField(10);
frame.add(num2Field);
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);
frame.add(calculateButton);
resultLabel = new JLabel("Result:");
frame.add(resultLabel);
resultField = new JTextField(10);
resultField.setEditable(false);
frame.add(resultField);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
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();
}
}
```
这个程序使用了 `actionPerformed(ActionEvent e)` 方法来实现按钮的响应事件。当用户点击“Calculate”按钮时,程序会将两个输入的值相乘并显示结果。希望对您有所帮助!
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)