首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java AWT 實現網上超市購物結算界面與邏輯

     編輯:Java 相關知識

使用 Java AWT 構建圖形化購物結算程序,演示視圖與邏輯分離、事件驅動編程、視窗組件佈局的基本功力。本文從需求分析到完整代碼實現,逐步拆解一個迷你收銀系統的構建過程。

一、需求與設計

  • 主視窗:標題「超市收銀系統」,尺寸 400×300,流式佈局
  • 組件:商品列表、數量輸入、加入按鈕、結算按鈕、總價顯示區
  • 事件:加入購物車、結算顯示總價、關閉視窗退出程序
  • 數據模型:Product(名稱、單價)、CartItem(商品、數量)

二、核心代碼實現

2.1 商品與購物車項目模型

class Product {
    private String name;
    private double price;
    // 建構子、getter/setter、toString()
}

class CartItem {
    private Product product;
    private int quantity;
    // 計算小計、getter/setter
}

2.2 主視窗類

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();
    }
}

三、關鍵技術點解析

  1. 模型-視圖分離:Product/CartItem 純數據類,UI 類僅負責顯示與事件分發
  2. 事件驅動:使用 ActionListener(按鈕)、WindowAdapter(視窗關閉)實現交互
  3. 佈局管理器:BorderLayout 整體分區,FlowLayout 區域內組件排列
  4. 集合存儲:ArrayList 動態管理商品與購物車項目
  5. Lambda 表達式:簡化匿名內部類寫法(Java 8+)

四、擴展方向

  • 持久化:嵌入 SQLite/H2 保存商品與訂單
  • 付款流程:整合支付寶/微信支付沙箱環境
  • 庫存管理:扣減庫存、低庫存預警
  • 報表統計:銷售額、熱銷商品排行
  • 遷移 Swing/JavaFX:獲得更豐富組件與現代化外觀

五、總結

這個迷你收銀系統雖簡單,卻包含了 GUI 開發的核心要素:組件佈局、事件處理、數據綁定、狀態管理。掌握 AWT 基礎後,輕鬆過渡到 Swing 或 JavaFX 開發企業級桌面應用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved