Java:输入单价和数量,点击计算按钮,在中间的标签上显示合计额
时间: 2024-03-20 14:40:51 浏览: 21
好的,我可以给你一个示例代码实现这个功能:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PriceCalculator extends JFrame implements ActionListener {
private JTextField priceField;
private JTextField quantityField;
private JLabel totalLabel;
public PriceCalculator() {
setTitle("Price Calculator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(3, 2));
JLabel priceLabel = new JLabel("单价:");
priceField = new JTextField();
JLabel quantityLabel = new JLabel("数量:");
quantityField = new JTextField();
JButton calculateButton = new JButton("计算");
calculateButton.addActionListener(this);
totalLabel = new JLabel();
panel.add(priceLabel);
panel.add(priceField);
panel.add(quantityLabel);
panel.add(quantityField);
panel.add(calculateButton);
panel.add(totalLabel);
add(panel);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("计算")) {
double price = Double.parseDouble(priceField.getText());
int quantity = Integer.parseInt(quantityField.getText());
double total = price * quantity;
totalLabel.setText("合计:" + total);
}
}
public static void main(String[] args) {
new PriceCalculator();
}
}
```
这个程序使用了 Java 的 Swing GUI 框架,创建了一个窗口,包含了单价、数量和合计三个组件,当用户点击“计算”按钮时,程序会根据输入的单价和数量计算出合计金额,并在中间的标签上显示出来。