使用 Java AWT 構建圖形化購物結算程序,演示視圖與邏輯分離、事件驅動編程、視窗組件佈局的基本功力。本文從需求分析到完整代碼實現,逐步拆解一個迷你收銀系統的構建過程。
Product(名稱、單價)、CartItem(商品、數量)class Product {
private String name;
private double price;
// 建構子、getter/setter、toString()
}
class CartItem {
private Product product;
private int quantity;
// 計算小計、getter/setter
}
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
public class SupermarketCheckout extends Frame {
private List products = new ArrayList<>();
private List cart = new ArrayList<>();
// 組件
private List productList;
private TextField qtyField;
private Button addBtn, checkoutBtn;
private TextArea displayArea;
private Label totalLabel;
public SupermarketCheckout() {
initData();
initUI();
addEvents();
}
private void initData() {
products.add(new Product("蘋果", 5.0));
products.add(new Product("香蕉", 3.5));
products.add(new Product("牛奶", 12.0));
products.add(new Product("麵包", 8.0));
}
private void initUI() {
setTitle("超市收銀系統");
setBounds(300, 200, 400, 300);
setLayout(new BorderLayout());
// 北部:商品選擇區
Panel north = new Panel(new FlowLayout());
productList = new List();
for (Product p : products) productList.add(p.getName() + " - $" + p.getPrice());
north.add(new Label("商品:"));
north.add(productList);
north.add(new Label("數量:"));
qtyField = new TextField("1", 3);
north.add(qtyField);
addBtn = new Button("加入購物車");
north.add(addBtn);
add(north, BorderLayout.NORTH);
// 中部:購物車明細
displayArea = new TextArea("", 10, 40, TextArea.SCROLLBARS_VERTICAL_ONLY);
displayArea.setEditable(false);
add(new ScrollPane(displayArea), BorderLayout.CENTER);
// 南部:結算區
Panel south = new Panel(new FlowLayout(FlowLayout.RIGHT));
checkoutBtn = new Button("結算付款");
totalLabel = new Label("總計: $0.00");
south.add(totalLabel);
south.add(checkoutBtn);
add(south, BorderLayout.SOUTH);
setVisible(true);
}
private void addEvents() {
// 關閉視窗事件
addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent e) { System.exit(0); }
});
// 加入購物車
addBtn.addActionListener(e -> {
int index = productList.getSelectedIndex();
if (index < 0) return;
try {
int qty = Integer.parseInt(qtyField.getText().trim());
if (qty <= 0) return;
Product p = products.get(index);
cart.add(new CartItem(p, qty));
refreshDisplay();
} catch (NumberFormatException ex) {
// 忽略非數字輸入
}
});
// 結算
checkoutBtn.addActionListener(e -> {
if (cart.isEmpty()) return;
double total = cart.stream().mapToDouble(CartItem::getSubtotal).sum();
totalLabel.setText(String.format("總計: $%.2f", total));
// 這裡可擴展:彈出付款對話框、生成訂單、清空購物車等
});
}
private void refreshDisplay() {
StringBuilder sb = new StringBuilder();
for (CartItem item : cart) {
sb.append(item.getProduct().getName())
.append(" x ").append(item.getQuantity())
.append(" = $").append(String.format("%.2f", item.getSubtotal()))
.append("\n");
}
displayArea.setText(sb.toString());
}
public static void main(String[] args) {
new SupermarketCheckout();
}
}
Product/CartItem 純數據類,UI 類僅負責顯示與事件分發ActionListener(按鈕)、WindowAdapter(視窗關閉)實現交互BorderLayout 整體分區,FlowLayout 區域內組件排列ArrayList 動態管理商品與購物車項目這個迷你收銀系統雖簡單,卻包含了 GUI 開發的核心要素:組件佈局、事件處理、數據綁定、狀態管理。掌握 AWT 基礎後,輕鬆過渡到 Swing 或 JavaFX 開發企業級桌面應用。