In this tutorial, we’ll build a BMI (Body Mass Index) and BMR (Basal Metabolic Rate) calculator in Java using Swing for the graphical user interface (GUI).
The app will allow users to input their weight, height, age, and gender to calculate their BMI and BMR.
Features of the BMI and BMR Calculator:
BMI Calculation: The app calculates BMI using the formula:
BMI = weight (kg) / height (m)
BMR Calculation: The app calculates BMR using the Mifflin-St Jeor equation:
For men:
BMR=10×weight (kg)+6.25×height (cm)−5×age+5
For women:
BMR=10×weight (kg)+6.25×height (cm)−5×age−161
The user inputs their weight, height, age, and gender.
The app displays the calculated BMI and BMR.
The app allows users to reset the input fields.
Complete Code of the App
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class BMIBMRCalculatorApp extends JFrame { // Components for input private JTextField weightField, heightField, ageField; private JRadioButton maleButton, femaleButton; private JButton calculateButton, resetButton; // Labels for output private JLabel bmiLabel, bmrLabel; // Constructor to set up the UI public BMIBMRCalculatorApp() { setTitle("BMI and BMR Calculator"); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // Center the window on the screen // Panel for input fields JPanel inputPanel = new JPanel(new GridLayout(6, 2, 10, 10)); inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // Input labels and fields inputPanel.add(new JLabel("Weight (kg):")); weightField = new JTextField(); inputPanel.add(weightField); inputPanel.add(new JLabel("Height (cm):")); heightField = new JTextField(); inputPanel.add(heightField); inputPanel.add(new JLabel("Age (years):")); ageField = new JTextField(); inputPanel.add(ageField); // Gender selection inputPanel.add(new JLabel("Gender:")); JPanel genderPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); ButtonGroup genderGroup = new ButtonGroup(); maleButton = new JRadioButton("Male", true); femaleButton = new JRadioButton("Female"); genderGroup.add(maleButton); genderGroup.add(femaleButton); genderPanel.add(maleButton); genderPanel.add(femaleButton); inputPanel.add(genderPanel); // Buttons for calculate and reset calculateButton = new JButton("Calculate"); resetButton = new JButton("Reset"); inputPanel.add(calculateButton); inputPanel.add(resetButton); // Panel for output labels JPanel outputPanel = new JPanel(new GridLayout(2, 1, 10, 10)); bmiLabel = new JLabel("BMI: "); bmrLabel = new JLabel("BMR: "); outputPanel.add(bmiLabel); outputPanel.add(bmrLabel); // Add action listeners calculateButton.addActionListener(new CalculateButtonListener()); resetButton.addActionListener(new ResetButtonListener()); // Set layout for the frame setLayout(new BorderLayout()); add(inputPanel, BorderLayout.CENTER); add(outputPanel, BorderLayout.SOUTH); setVisible(true); } // Method to calculate and display BMI and BMR private void calculateBMIandBMR() { try { double weight = Double.parseDouble(weightField.getText()); double height = Double.parseDouble(heightField.getText()) / 100.0; // Convert height to meters int age = Integer.parseInt(ageField.getText()); // Calculate BMI double bmi = weight / (height * height); // Calculate BMR based on gender double bmr; if (maleButton.isSelected()) { bmr = 10 * weight + 6.25 * (height * 100) - 5 * age + 5; // For men } else { bmr = 10 * weight + 6.25 * (height * 100) - 5 * age - 161; // For women } // Display results bmiLabel.setText(String.format("BMI: %.2f", bmi)); bmrLabel.setText(String.format("BMR: %.2f", bmr)); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(this, "Please enter valid numeric values.", "Input Error", JOptionPane.ERROR_MESSAGE); } } // Action listener for the calculate button private class CalculateButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { calculateBMIandBMR(); } } // Action listener for the reset button private class ResetButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { weightField.setText(""); heightField.setText(""); ageField.setText(""); bmiLabel.setText("BMI: "); bmrLabel.setText("BMR: "); } } // Main method to run the app public static void main(String[] args) { SwingUtilities.invokeLater(() -> new BMIBMRCalculatorApp()); } }
Explanation of the Code
1. Import Statements
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; javax.swing.*: Imports all Swing components (JFrame, JButton, JTextField, JLabel, etc.). java.awt.*: Imports AWT components and layout managers (GridLayout, FlowLayout, BorderLayout). java.awt.event.*: Imports event listener classes for handling button clicks.
2. Class Declaration and Instance Variables
public class BMIBMRCalculatorApp extends JFrame { // Components for input private JTextField weightField, heightField, ageField; private JRadioButton maleButton, femaleButton; private JButton calculateButton, resetButton; // Labels for output private JLabel bmiLabel, bmrLabel; } JTextField weightField, heightField, ageField: Text fields for user input (weight, height, and age). JRadioButton maleButton, femaleButton: Radio buttons to select gender. JButton calculateButton, resetButton: Buttons to trigger the calculation and reset the input fields. JLabel bmiLabel, bmrLabel: Labels to display the calculated BMI and BMR.
3. Constructor
public BMIBMRCalculatorApp() { setTitle("BMI and BMR Calculator"); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // Panel for input fields JPanel inputPanel = new JPanel(new GridLayout(6, 2, 10, 10)); inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // Input labels and fields inputPanel.add(new JLabel("Weight (kg):")); weightField = new JTextField(); inputPanel.add(weightField); inputPanel.add(new JLabel("Height (cm):")); heightField = new JTextField(); inputPanel.add(heightField); inputPanel.add(new JLabel("Age (years):")); ageField = new JTextField(); inputPanel.add(ageField); // Gender selection inputPanel.add(new JLabel("Gender:")); JPanel genderPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); ButtonGroup genderGroup = new ButtonGroup(); maleButton = new JRadioButton("Male", true); femaleButton = new JRadioButton("Female"); genderGroup.add(maleButton); genderGroup.add(femaleButton); genderPanel.add(maleButton); genderPanel.add(femaleButton); inputPanel.add(genderPanel); // Buttons for calculate and reset calculateButton = new JButton("Calculate"); resetButton = new JButton("Reset"); inputPanel.add(calculateButton); inputPanel.add(resetButton); // Panel for output labels JPanel outputPanel = new JPanel(new GridLayout(2, 1, 10, 10)); bmiLabel = new JLabel("BMI: "); bmrLabel = new JLabel("BMR: "); outputPanel.add(bmiLabel); outputPanel.add(bmrLabel); // Add action listeners calculateButton.addActionListener(new CalculateButtonListener()); resetButton.addActionListener(new ResetButtonListener()); // Set layout for the frame setLayout(new BorderLayout()); add(inputPanel, BorderLayout.CENTER); add(outputPanel, BorderLayout.SOUTH); setVisible(true); }
Frame Setup:
setTitle(“BMI and BMR Calculator”): Sets the window title.
setSize(400, 300): Sets the window size.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures the program exits when the window is closed.
setLocationRelativeTo(null): Centers the window on the screen.
Input Panel Setup:
JTextField: Text fields for weight, height, and age input.
JRadioButton: Radio buttons for selecting gender (Male/Female).
JButton: Two buttons, one for calculating BMI and BMR and one for resetting the fields.
Output Panel Setup:
JLabel: Labels to display the calculated BMI and BMR.
4. calculateBMIandBMR() Method
private void calculateBMIandBMR() { try { double weight = Double.parseDouble(weightField.getText()); double height = Double.parseDouble(heightField.getText()) / 100.0; // Convert height to meters int age = Integer.parseInt(ageField.getText()); // Calculate BMI double bmi = weight / (height * height); // Calculate BMR based on gender double bmr; if (maleButton.isSelected()) { bmr = 10 * weight + 6.25 * (height * 100) - 5 * age + 5; // For men } else { bmr = 10 * weight + 6.25 * (height * 100) - 5 * age - 161; // For women } // Display results bmiLabel.setText(String.format("BMI: %.2f", bmi)); bmrLabel.setText(String.format("BMR: %.2f", bmr)); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(this, "Please enter valid numeric values.", "Input Error", JOptionPane.ERROR_MESSAGE); } }
BMI Calculation:
Formula: BMI = weight / (height in meters)^2.
The height is entered in centimeters by the user, so it is converted to meters (height / 100).
BMI is then calculated and displayed using bmiLabel.
BMR Calculation:
The Mifflin-St Jeor Equation is used:
For men: BMR = 10 * weight + 6.25 * height (in cm) – 5 * age + 5
For women: BMR = 10 * weight + 6.25 * height (in cm) – 5 * age – 161
The calculated BMR is displayed using bmrLabel.
Error Handling:
If the input values are invalid (non-numeric), a message dialog is displayed using JOptionPane.
5. Action Listeners
// Action listener for the calculate button private class CalculateButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { calculateBMIandBMR(); } } // Action listener for the reset button private class ResetButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { weightField.setText(""); heightField.setText(""); ageField.setText(""); bmiLabel.setText("BMI: "); bmrLabel.setText("BMR: "); } }
CalculateButtonListener:
Calls the calculateBMIandBMR() method when the user clicks the “Calculate” button.
ResetButtonListener:
Clears all input fields and resets the output labels when the user clicks the “Reset” button.
6. Main Method
public static void main(String[] args) { SwingUtilities.invokeLater(() -> new BMIBMRCalculatorApp()); }
SwingUtilities.invokeLater(): Ensures that the GUI runs on the Event Dispatch Thread (EDT), which is necessary for thread-safe updates in Swing applications.
new BMIBMRCalculatorApp(): Creates and launches an instance of the BMI/BMR calculator app.
Customization Ideas
1. Allow Different Units
Add a dropdown or toggle for users to select between metric units (kg, cm) and imperial units (lbs, inches).
Convert between units in the calculation methods.
2. Include Activity Level for BMR
Add an option to input activity level (e.g., sedentary, light activity, moderate activity).
Adjust the BMR formula to calculate total daily energy expenditure (TDEE) based on the activity level.
3. Add Validation for Input Values
Add more detailed validation to ensure inputs are within a reasonable range (e.g., weight and height are positive numbers).
Display specific error messages for invalid inputs.
4. Customize the Appearance
Change the fonts, colors, and layout to improve the UI.
For example, you can change the background color of the window or make the buttons more visually appealing.
Conclusion
This tutorial demonstrates how to create a BMI and BMR Calculator App using Java Swing. The project covers:
Creating a GUI with Swing components (JFrame, JLabel, JTextField, JRadioButton, JButton).
Handling user input and performing calculations based on the inputs.
Displaying output dynamically based on the user’s actions.
Handling events with action listeners.
You can extend this basic app by adding more features, customizing the UI, or allowing the app to handle more complex calculations like total daily energy expenditure (TDEE) based on activity level.