首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java Swing 實作簡易 BMI 計算器:完整代碼與算法解析

     編輯:程式設計綜合問答

前言

在 Java 圖形界面開發中,實作一個簡易的 BMI(Body Mass Index)計算器是入門級的經典練習。本文將詳細說明如何設計算法、處理用戶輸入、按鈕事件監聽,並提供完整可運行的代碼示例。

核心需求

  • 提供身高(米)與體重(千克)的輸入框
  • 點擊「評估」按鈕後自動計算 BMI 值
  • 根據 BMI 範圍顯示「瘦」、「正常」或「胖」
  • 包含輸入驗證(非空、正數)

算法設計

BMI 計算公式為:BMI = 體重 / (身高 * 身高)。判斷邏輯如下:

if (bmi < 18.5) → 瘦
else if (bmi < 24) → 正常
else → 胖

關鍵技術點:ActionListener 事件處理

核心在於為「評估」按鈕註冊 ActionListener,在 actionPerformed 方法中獲取文本框數據、驗證、計算並更新結果欄位。

完整代碼實現

public class BMI extends JFrame {
    private JLabel lblHeight, lblWeight, lblBMI, lblResult;
    private JTextField txtHeight, txtWeight, txtBMI, txtResult;
    private JButton btnRun;
    private JPanel pnlMain;
    private DecimalFormat dformat = new DecimalFormat("#.00");

    public BMI() {
        // 初始化組件
        lblHeight = new JLabel("身高(米/m)");
        txtHeight = new JTextField(10);
        lblWeight = new JLabel("體重(千克/kg)");
        txtWeight = new JTextField(10);
        lblBMI = new JLabel("健康值(BMI)");
        txtBMI = new JTextField(10);
        lblResult = new JLabel("結果");
        txtResult = new JTextField(10);
        btnRun = new JButton("評估");
        pnlMain = new JPanel();
        pnlMain.setLayout(null);

        // 設置組件位置與大小
        lblHeight.setBounds(100, 50, 80, 25);
        txtHeight.setBounds(200, 50, 100, 25);
        lblWeight.setBounds(100, 80, 80, 25);
        txtWeight.setBounds(200, 80, 100, 25);
        lblBMI.setBounds(100, 110, 80, 25);
        txtBMI.setBounds(200, 110, 100, 25);
        lblResult.setBounds(100, 170, 80, 25);
        txtResult.setBounds(200, 170, 100, 25);
        btnRun.setBounds(150, 140, 80, 25);

        // 添加到面板
        pnlMain.add(lblHeight); pnlMain.add(txtHeight);
        pnlMain.add(lblWeight); pnlMain.add(txtWeight);
        pnlMain.add(lblBMI); pnlMain.add(txtBMI);
        pnlMain.add(lblResult); pnlMain.add(txtResult);
        pnlMain.add(btnRun);

        this.setContentPane(pnlMain);
        setSize(400, 300);
        setTitle("健康評估");
        setVisible(true);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 核心:按鈕事件監聽
        btnRun.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 輸入驗證
                if (txtWeight.getText().trim().isEmpty()) {
                    JOptionPane.showMessageDialog(null, "體重為空,請輸入一個正值體重!");
                    return;
                }
                if (txtHeight.getText().trim().isEmpty()) {
                    JOptionPane.showMessageDialog(null, "身高為空,請輸入一個正值身高!");
                    return;
                }

                double weight = Double.parseDouble(txtWeight.getText());
                if (weight <= 0) {
                    JOptionPane.showMessageDialog(null, "體重必須大於 0。");
                    return;
                }
                double height = Double.parseDouble(txtHeight.getText());
                if (height <= 0) {
                    JOptionPane.showMessageDialog(null, "身高必須大於 0。");
                    return;
                }

                // 計算 BMI
                double bmi = weight / (height * height);
                txtBMI.setText(dformat.format(bmi));
                txtResult.setText(getResult(bmi));
            }
        });
    }

    private String getResult(double bmi) {
        if (bmi < 18.5) return "瘦";
        else if (bmi < 24) return "正常";
        else return "胖";
    }

    public static void main(String[] args) {
        new BMI();
    }
}

界面截圖

BMI 計算器界面

運行效果圖

常見問題與優化建議

  • 使用 trim() 去除輸入首尾空格,避免 " " 通過驗證
  • 捕獲 NumberFormatException 處理非數字輸入
  • 考慮使用 JFormattedTextField 限制輸入格式
  • 結果欄位設置為不可編輯(setEditable(false))

總結

通過本例可掌握 Java Swing 基本佈局、事件監聽模型、數據驗證與簡單業務邏輯封裝。此模式可擴展至更複雜的表單應用開發。

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