Here is a Java Program to Find the Body Mass Index Using AWT and Swing Classes
Output of Above Java Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class BMI extends JFrame {
public static void main(String[] args) {
BMI window = new BMI();
window.setVisible(true);
}
private JTextField _mField = new JTextField(4); // height
private JTextField _kgField = new JTextField(4); // weight
private JTextField _bmiField = new JTextField(4); // BMI
/****************constructor********************/
public BMI() {
//Create button and add action listener.
JButton bmiButton = new JButton("Compute BMI");
bmiButton.addActionListener(new BMIListener());
//Set layout and add components.
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(new JLabel("Weight in kilograms"));
content.add(_kgField);
content.add(new JLabel("Height in meters"));
content.add(_mField);
content.add(bmiButton);
content.add(new JLabel("Your BMI is"));
content.add(_bmiField);
//Set the window characteristics.
setContentPane(content);
setTitle("Body Mass Index");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack(); // Do layout.
setLocationRelativeTo(null); // Center window.
}
/******************* inner class BMIListener *********************/
// Inner class is used to access components.
// BMI is converted to int to eliminate excess "accuracy".
private class BMIListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
double kilograms = Double.parseDouble(_kgField.getText());
double meters = Double.parseDouble(_mField.getText());
int bmi = (int)computeBMI(kilograms, meters);
_bmiField.setText("" + bmi);
}
}
//logic method computeBMI
public static double computeBMI(double weight, double height) {
return weight / (height * height);
}
}
Output of Above Java Program
