实现如下图功能,输入单价和数量,点击计算按钮,在中间的标签上显示合计额。
时间: 2024-04-03 18:35:06 浏览: 25
好的,我可以给您提供一个 Java Swing 的实现方案,实现如下图所示的计算器功能:
![计算器](https://img-blog.csdnimg.cn/2021120113575978.png)
首先,我们需要一个 JFrame 窗口,窗口中包含一个 JPanel 容器,容器中包含标签、文本框和按钮等组件,代码如下:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame {
private JPanel panel; // 面板
private JLabel priceLabel, quantityLabel, resultLabel; // 标签
private JTextField priceField, quantityField; // 文本框
private JButton calculateButton; // 按钮
public Calculator() {
// 初始化窗口
super("计算器");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 初始化面板
panel = new JPanel(new GridLayout(3, 2, 5, 5));
// 初始化标签和文本框
priceLabel = new JLabel("单价:");
priceField = new JTextField();
quantityLabel = new JLabel("数量:");
quantityField = new JTextField();
resultLabel = new JLabel("合计:");
// 初始化按钮
calculateButton = new JButton("计算");
calculateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 计算合计金额
double price = Double.parseDouble(priceField.getText());
int quantity = Integer.parseInt(quantityField.getText());
double result = price * quantity;
resultLabel.setText(String.format("合计:%s", result));
}
});
// 将组件添加到面板中
panel.add(priceLabel);
panel.add(priceField);
panel.add(quantityLabel);
panel.add(quantityField);
panel.add(resultLabel);
panel.add(calculateButton);
// 将面板添加到窗口中
setContentPane(panel);
// 显示窗口
setVisible(true);
}
public static void main(String[] args) {
new Calculator();
}
}
```
在计算按钮的监听器中,我们可以获取单价和数量的输入值,并计算出合计金额,最后将结果显示在标签上。
另外,为了美观,我们使用了 GridLayout 布局管理器,将面板划分为 3 行 2 列,每个组件之间间隔为 5 像素。
希望这个回答可以帮助到您,如有疑问请随时追问。