skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Sunday, February 12, 2012

Find the Body Mass Index Using AWT and Swing Classes

Posted by Admin at 12:46 AM – 0 comments
 
Here is a Java Program to Find the Body Mass Index Using AWT and Swing Classes

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









Labels: Java AWT Example , Java Swing Example , JFrame Example

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger