This is my first question here and this is my working Body Mass Index Swing Calculator. Any improvement or recommendation is welcome.
// Metric units
// Weight in kg
// Height in meters
import javax.swing.*;
import java.awt.*;
public class MainProgram {
public static void calculateIMC(DataPanel in){
String salida = in.weight.getText();
System.out.print(salida);
}
public static void main(String[] args) {
JFrame frame = new JFrame("BMI");
DataPanel in = new DataPanel();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setBounds(150,150,500,400);
frame.setLayout(new GridLayout(0,2));
// frame.pack();
frame.add(in);
System.out.println(Grade.getGrade(33.4));
}
}
This is an enum example
public enum Grade {
INS("Insuficient Weight",18.5),
NRM("Normal Wight",24.9),
SBR1("Overweight Grade 1",26.9),
SBR2("Overweight Grade 2: Probesity",29.9),
OBS1("Obesity Grade 1",34.9),
OBS2("Obesity Grade 2",3.9),
OBS3("Obesity Grade 3: Morbid",49.9),
OBS4("Obesity Grade 4: Extreme",50);
private final String title;
private final double lim;
public String getTitle() {
return title;
}
public double getLim() {
return lim;
}
Grade(String s, double i) {
title = s;
lim = i;
}
public static String getGrade(double value){
for (int i=0; i < Grade.values().length;i++){
if(value > Grade.OBS4.getLim()){
return Grade.OBS4.getTitle();
} else if(value < Grade.INS.getLim()){
return Grade.INS.getTitle();
} else if(value > Grade.values()[i].getLim() && value < Grade.values()[i+1].getLim()){
return Grade.values()[i+1].getTitle();
}
}
return null;
}
}
And the Panel
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DataPanel extends JPanel {
JTextField weight = new JTextField(10);
JTextField height = new JTextField(10);
JButton calculate = new JButton("Calculate");
DataPanel(){
initialize();
}
private void initialize() {
add(new JLabel("Weight: "));
add(weight);
add(new JLabel("Height: "));
add(height);
add(calculate);
calculate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double w=Double.parseDouble(weight.getText());
double h=Double.parseDouble(height.getText());
double bmi=w/(h*h);
JOptionPane.showMessageDialog(null,"Your BMI is: "+String.format("%.2f",bmi));
JOptionPane.showMessageDialog(null,"Your Grade is: "+Grade.getGrade(bmi));
}
});
setVisible(true);
setBorder(BorderFactory.createTitledBorder("BMI"));
// setBounds();
// setLayout(new GridLayout(0,2));
setMaximumSize(new Dimension(30,100));
}
}