java - 使用公制方程计算 BMI,如何在 Java 中使用 GUI 转换英制测量值

标签 java swing user-interface

我是 Java 新手,必须创建一个 BMI 计算器,允许用户输入公制或英制测量值,并使用计算 BMI 的方程之一来计算 BMI。我已经使用了公制计算,并且公制测量结果显示正确。我现在需要将英制测量值转换为公制,然后使用现有的公制 BMI 计算,显示答案。如果有人能提供帮助,我将不胜感激。

这是我到目前为止所拥有的:

import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import java.awt.Font;

public class BMIFrame extends JFrame{
  // Create instructions label
  private JLabel instructions = new JLabel("<html>To calculate your Body 
     Mass Index (BMI), please "
    + "enter your weight and height in the fields provided in either 
  Imperial or Metric measurements.</html>");

    // Metric section labels and fields
    private JLabel metricHeading = new JLabel("Metric");
    private JLabel metricWeight = new JLabel("Enter your Weight:");
    private JTextField metTextWeight = new JTextField("0");
    private JLabel weightKg = new JLabel("kgs");
    private JLabel metricHeight = new JLabel("Enter your Height:");
    private JTextField metTextHeight = new JTextField("0");
    private JLabel heightCm = new JLabel("cms");

    // Imperial section labels and fields
    private JLabel imperialHeading = new JLabel("Imperial");
    private JLabel imperialWeight = new JLabel("Enter your Weight:");
    private JTextField impTextWeight = new JTextField("0");
    private JLabel weightSt = new JLabel("st");
    private JTextField impTextWeight2 = new JTextField("0");
    private JLabel weightLbs = new JLabel("lbs");
    private JLabel imperialHeight = new JLabel("Enter your Height:");
    private JTextField impTextHeight = new JTextField("0");
    private JLabel heightFt = new JLabel("ft");
    private JTextField impTextHeight2= new JTextField("0");
    private JLabel heightIns = new JLabel("ins");

    private JButton calculateButton = new JButton("Calculate BMI");
    private JButton clearButton = new JButton("Clear");
    private JButton quitButton = new JButton("Quit");

    private JLabel bmiInfoHeading = new JLabel("BMI Values");
    private JLabel bmiInfoUnder = new JLabel("Below 18.5 = Underweight");
    private JLabel bmiInfoNormal = new JLabel("18.5 - 24.9 = Normal");
    private JLabel bmiInfoOver = new JLabel("25.0 - 29.9 = Overweight");
    private JLabel bmiInfoObese = new JLabel("30.0 + = Obese");

    // create a this is your result label
    private JLabel bmiResult = new JLabel("Your BMI is ");
    private JTextField resultField = new JTextField("0");

    public BMIFrame() {
        setLayout(null);

        // Add instructions
        instructions.setBounds(5, 5, 475, 38);
        instructions.setBackground(getBackground());
        instructions.setFont(new Font("Arial", Font.PLAIN, 13));
        add(instructions);

        // Add Metric heading
        metricHeading.setBounds(90, -25, 225, 200);
        metricHeading.setFont(new Font("Arial", Font.BOLD, 14));
        add(metricHeading);

        // Add Metric Weight Label
        metricWeight.setBounds(5, 5, 225, 200);
        metricWeight.setFont(new Font("Arial", Font.PLAIN, 13));
        add(metricWeight);

        // Add Metric Weight input field
        metTextWeight.setBounds(120, 92, 50, 25);
        metTextWeight.setHorizontalAlignment(SwingConstants.RIGHT);
        add(metTextWeight);

        // Add Kilogram label to weight field
        weightKg.setBounds(172, 5, 225, 200);
        weightKg.setFont(new Font("Arial", Font.PLAIN, 13));
        add(weightKg);

        // Add Metric Height Label
        metricHeight.setBounds(5, 40, 225, 200);
        metricHeight.setFont(new Font("Arial", Font.PLAIN, 13));
        add(metricHeight);

        // Add Metric Height input field
        metTextHeight.setBounds(120, 127, 50, 25);
        metTextHeight.setHorizontalAlignment(SwingConstants.RIGHT);
        add(metTextHeight);

        // Add Centimetres label to weight field
        heightCm.setBounds(172, 40, 225, 200);
        heightCm.setFont(new Font("Arial", Font.PLAIN, 13));
        add(heightCm);

        // Add imperial measurements fields
        imperialHeading.setBounds(330, -25, 225, 200);
        imperialHeading.setFont(new Font("Arial", Font.BOLD, 14));
        add(imperialHeading);

        // Add Imperial Weight Label
        imperialWeight.setBounds(225, 5, 225, 200);
        imperialWeight.setFont(new Font("Arial", Font.PLAIN, 13));
        add(imperialWeight);

        // Add Imperial Weight input field
        impTextWeight.setBounds(335, 92, 50, 25);
        impTextWeight.setHorizontalAlignment(SwingConstants.RIGHT);
        add(impTextWeight);

        // Add Stone label to weight field
        weightSt.setBounds(385, 5, 225, 200);
        weightSt.setFont(new Font("Arial", Font.PLAIN, 13));
        add(weightSt);

        // Add second Imperial Weight input field
        impTextWeight2.setBounds(400, 92, 50, 25);
        impTextWeight2.setHorizontalAlignment(SwingConstants.RIGHT);
        add(impTextWeight2);

        // Add Pounds label to weight field
        weightLbs.setBounds(451, 5, 225, 200);
        weightLbs.setFont(new Font("Arial", Font.PLAIN, 13));
        add(weightLbs);

        // Add Imperial Height Label
        imperialHeight.setBounds(225, 40, 225, 200);
        imperialHeight.setFont(new Font("Arial", Font.PLAIN, 13));
        add(imperialHeight);

        // Add Imperial Height input field
        impTextHeight.setBounds(335, 127, 50, 25);
        impTextHeight.setHorizontalAlignment(SwingConstants.RIGHT);
        add(impTextHeight);

        // Add Feet label to weight field
        heightFt.setBounds(386, 40, 225, 200);
        heightFt.setFont(new Font("Arial", Font.PLAIN, 13));
        add(heightFt);

        // Add Imperial Height input field
        impTextHeight2.setBounds(400, 127, 50, 25);
        impTextHeight2.setHorizontalAlignment(SwingConstants.RIGHT);
        add(impTextHeight2);

        // Add Inches label to height field
        heightIns.setBounds(451, 40, 225, 200);
        heightIns.setFont(new Font("Arial", Font.PLAIN, 13));
        add(heightIns);

        // Add Calculate button
        calculateButton.setBounds(175, 175, 125, 50);
        add(calculateButton);

        // Add Clear button
        clearButton.setBounds(120, 360, 115, 30);
        add(clearButton);

        // Add Quit button
        quitButton.setBounds(240, 360, 115, 30);
        add(quitButton);

        // Result label
        bmiResult.setBounds(10, 240, 80, 50);
        add(bmiResult);

        // Add result field
        resultField.setBounds(86, 243, 80, 40);
        resultField.setHorizontalAlignment(SwingConstants.CENTER);
        resultField.setEditable(false);
        add(resultField);

        // BMI values display
        bmiInfoHeading.setBounds(345, 230, 80, 50);
        add(bmiInfoHeading);

        bmiInfoUnder.setBounds(300, 255, 200, 50);
        bmiInfoUnder.setFont(new Font("Arial", Font.PLAIN, 13));
        add(bmiInfoUnder);

        bmiInfoNormal.setBounds(300, 275, 200, 50);
        bmiInfoNormal.setFont(new Font("Arial", Font.PLAIN, 13));
        add(bmiInfoNormal);

        bmiInfoOver.setBounds(300, 295, 200, 50);
        bmiInfoOver.setFont(new Font("Arial", Font.PLAIN, 13));
        add(bmiInfoOver);

        bmiInfoObese.setBounds(300, 315, 200, 50);
        bmiInfoObese.setFont(new Font("Arial", Font.PLAIN, 13));
        add(bmiInfoObese);

        ButtonHandler bh = new ButtonHandler();
        calculateButton.addActionListener(bh);
        clearButton.addActionListener(bh);
        quitButton.addActionListener(bh);

    } // end of constructor

    // private inner class ButtonHandler
    private class ButtonHandler implements ActionListener{
        public void actionPerformed(ActionEvent event) {
            if (event.getSource() == quitButton)
                System.exit(0);
            else if (event.getSource() == clearButton) {
                metTextWeight.setText("0");
                metTextHeight.setText("0");
                impTextWeight.setText("0");
                impTextWeight2.setText("0");
                impTextHeight.setText("0");
                impTextHeight2.setText("0");
                resultField.setText("0");
                return;
            }

            try {
                double metW1 = Double.parseDouble(metTextWeight.getText());
                double metH1 = Double.parseDouble(metTextHeight.getText());
                double impW1 = Double.parseDouble(impTextWeight.getText());
                double impW2 = Double.parseDouble(impTextWeight2.getText());
                double impH1 = Double.parseDouble(impTextHeight.getText());
                double impH2 = Double.parseDouble(impTextHeight2.getText());

                double result = 0;

                if (event.getSource() == calculateButton)
                    result = (metW1 / (metH1 * metH1) * 10000);

                String answers = String.format("%.1f", result);

                resultField.setText(answers);
            } // end of try method
            catch(Exception ex) {
                JOptionPane.showMessageDialog(BMIFrame.this, ex.toString()
                    , "Error Message", JOptionPane.WARNING_MESSAGE);
            } // end of catch method
        } // end of method actionPerformed
    } // end of inner class ButtonHandler
} //end of class BMIFrame

最佳答案

我建议采用不同的方法,这应该有助于简化代码。考虑这个接口(interface):

public interface BMICalculator {
    public double calculate(double height, double weight);
}

还有两个实现:

public class MetricBMICalculator implements BMICalculator {
    public double calculate(double heightCentimeters, double weightKilograms) {
      // convert as needed, calculate, and return...
    }
}

public class ImperialBMICalculator implements BMICalculator {
    public double calculate(double heightFeet, double weightPounds) {
      // convert as needed, calculate, and return...
    }
}

用户界面内有一个单位切换开关,可以在公制和英制之间切换。这导致只需要一个体重输入字段和一个高度输入字段。当触发切换时,相关标签的文本会发生变化,并且上述接口(interface)的实现也会发生变化。

关于java - 使用公制方程计算 BMI,如何在 Java 中使用 GUI 转换英制测量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47557088/

相关文章:

java - 如何使滚动 Pane 静态?

java - 用于 double 的 JSlider

java - Android 测试构建错误 : Multiple dex files define Landroid/support/test/BuildConfig

java - 在知道@NonNull 注释的Eclipse 中自动生成equals 和hashCode

java - Swing 组件未按照布局对齐

java - GridBagLayout 不显示 JTextArea,并在中心显示面板

MATLAB - 编辑框的回调执行

Windows系统编程

java - 使用 Visual Studio Code 远程扩展运行 JavaFX

java - 如何显示通知栏?