Hi friend,
Code to solve the problem :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BmiInSwing implements ActionListener {
JFrame frame;
JPanel panel;
JTextField weightText;
JLabel celLabel, fahLabel;
JButton calBmi;
JTextField heightText;
public BmiInSwing() {
frame = new JFrame("Calculate BMI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(180, 80));
panel = new JPanel(new GridLayout(3, 2));
panel.setBorder(BorderFactory.createEmptyBorder(60,
60,
20,
60)
);
addItems();
frame.getRootPane().setDefaultButton(calBmi);
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private void addItems() {
fahLabel = new JLabel("Weight", SwingConstants.LEFT);
weightText = new JTextField(20);
calBmi = new JButton("Calculate");
celLabel = new JLabel("Height", SwingConstants.LEFT);
heightText = new JTextField(20);
calBmi.addActionListener(this);
panel=new JPanel(new GridLayout(4,1));
panel.add(fahLabel);
panel.add(weightText);
panel.add(celLabel);
panel.add(heightText);
panel.add(calBmi);
celLabel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 5));
fahLabel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 5));
}
public void actionPerformed(ActionEvent event) {
String selected=weightText.getText();
String selected1=heightText.getText();
if (selected.equals("")){
heightText.setText("");
JOptionPane.showMessageDialog(null,"Enter the Weight value");
}
else if(selected1.equals("")){
heightText.setText("");
JOptionPane.showMessageDialog(null,"Enter the Height value");
}
else
{
String strOutput="";
double BMI = Double.parseDouble(selected) / Double.parseDouble(selected1);
double idealBMI = 21.75;
double idealWeight = idealBMI * Double.parseDouble(selected1);
String strbmi = Double.toString(BMI);
String strIdealBMI = Double.toString(idealBMI);
String strIdealWeight = Double.toString(idealWeight);
String msg="";
if(BMI<15)
{
msg = "Person to be Starvation";
}
else if(BMI>=15 && BMI<18.5)
{
msg = "Person to be Underweight";
}
else if(BMI>=18.5 && BMI<25)
{
msg = "Person to be Normal";
}
else if(BMI>=25 && BMI<30)
{
msg = "Person to be Overweight";
}
else if(BMI>=30 && BMI<40)
{
msg = "Person to be Obese";
}
else if(BMI>=40)
{
msg = "Person to be Morbidly Obese";
}
strOutput += "BMI : " + BMI+"\n";
strOutput += "Ideal BMI : " + idealBMI+"\n";
strOutput += "Ideal Weight : " + strIdealWeight+"\n";
strOutput += "Output : " + msg+"\n";
JOptionPane.showMessageDialog(null,strOutput);
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
BmiInSwing converter = new BmiInSwing();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
For more information on java visit to :
http://www.roseindia.net/java/Thanks