Java图形界面 简易BMI计算器怎样设计算法

• 写回答

3条回答默认 最新

• JonsonJiao 2015-06-01 05:59
关注

你的核心问题是如何对按钮进行响应，需要看下ActionListener的相关方法。

``````    public class BMI extends JFrame{

private JLabel lblHeight;
private JLabel lblWeight;
private JLabel lblBMI;
private JLabel lblResult;

private JButton btnRun;
private JPanel pnlMain;
private JTextField txtHeight;
private JTextField txtWeight;
private JTextField txtBMI;
private JTextField txtResult;
DecimalFormat dformat = new DecimalFormat("#.00");
public BMI(){
lblHeight = new JLabel("身高(米/m)");
txtHeight = new JTextField(10);
lblWeight = new JLabel("体重(千克/kg)");
txtWeight = new JTextField(10);
lblBMI = new JLabel("健康值(BMI)");
txtBMI = new JTextField(10);
lblResult = new JLabel("结果");
txtResult = new JTextField(10);
btnRun = new JButton("评估");
pnlMain = new JPanel();
pnlMain.setLayout(null);
lblHeight.setBounds(100, 50, 80, 25);
txtHeight.setBounds(200, 50, 100, 25);
lblWeight.setBounds(100, 80, 80, 25);
txtWeight.setBounds(200, 80, 100, 25);
lblBMI.setBounds(100, 110, 80, 25);
txtBMI.setBounds(200, 110, 100, 25);
lblResult.setBounds(100, 170, 80, 25);
txtResult.setBounds(200, 170, 100, 25);
btnRun.setBounds(150, 140, 80, 25);

this.setContentPane(pnlMain);
setSize(400,300);
setTitle("健康评估");
setVisible(true);
setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if( txtWeight.getText() == null){
JOptionPane.showMessageDialog(null, "身高为空，请输入一个正值身高！");
return;
}
if( txtHeight.getText() == null){
JOptionPane.showMessageDialog(null, "体重为空，请输入一个正值体重！");
return;
}
double weight = Double.valueOf(txtWeight.getText());
if(weight <= 0 ){
JOptionPane.showMessageDialog(null, "体重为0，请输入一个正值体重。");
return;
}
double height = Double.valueOf(txtHeight.getText());
if(height <= 0 ){
JOptionPane.showMessageDialog(null, "身高为0，请输入一个正值身高。");
return;
}
double bmi = weight/height/height;
txtBMI.setText(dformat.format(bmi));
txtResult.setText(getResult(bmi));
}

});
}
private String getResult(double bmi) {
// TODO Auto-generated method stub
if(bmi < 18.5){
return "瘦";
}else if(bmi>=18.5 && bmi < 24){
return "正常";
}else{
return "胖";
}
}

public static void main(String[] args) {
new BMI();
}
}
``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

悬赏问题

• ¥85 3559A sensor时间同步
• ¥15 IGH主站与elmo驱动器连接时，pdo映射后无法输入输出
• ¥100 Android应用如何动态绑定邀请码
• ¥15 grbl用"!"命令停止移动后，怎么重置？
• ¥15 自己配的nginx 正向代理一直失败（相关搜索：谷歌浏览器|拒绝连接）