用awt方法,输入单价和数量,点击计算按钮,在中间的标签上显示合计额。Java
时间: 2024-03-20 18:40:23 浏览: 15
好的,我可以帮你实现这个功能。首先,你需要在界面上添加一个标签、两个文本框和一个按钮。标签用来显示合计额,两个文本框用来输入单价和数量,按钮用来触发计算。
下面是实现该功能的代码:
```java
import java.awt.*;
import java.awt.event.*;
public class PriceCalculator extends Frame implements ActionListener {
private TextField priceField, quantityField;
private Label totalLabel;
public PriceCalculator() {
super("Price Calculator");
// 设置布局为BorderLayout
setLayout(new BorderLayout());
// 添加单价和数量输入框
Panel inputPanel = new Panel(new FlowLayout());
inputPanel.add(new Label("单价"));
priceField = new TextField(10);
inputPanel.add(priceField);
inputPanel.add(new Label("数量"));
quantityField = new TextField(10);
inputPanel.add(quantityField);
add(inputPanel, BorderLayout.NORTH);
// 添加计算按钮
Panel buttonPanel = new Panel(new FlowLayout());
Button calculateButton = new Button("计算");
calculateButton.addActionListener(this);
buttonPanel.add(calculateButton);
add(buttonPanel, BorderLayout.CENTER);
// 添加合计额标签
totalLabel = new Label("合计额:0");
add(totalLabel, BorderLayout.SOUTH);
// 设置窗口大小和可见性
setSize(300, 150);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// 获取单价和数量
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();
}
}
```
你可以将上述代码保存到名为`PriceCalculator.java`的文件中,然后在命令行中编译并运行它。在Windows中,使用以下命令:
```
javac PriceCalculator.java
java PriceCalculator
```
在macOS或Linux中,使用以下命令:
```
javac PriceCalculator.java
java PriceCalculator
```
这将启动一个图形界面应用程序,你可以在其中输入单价和数量,然后点击计算按钮,应用程序会在中间的标签上显示合计额。