我正在尝试用 Java制作一个BMI计算器。然而,首先我正在玩一些 Jframe 的东西,它似乎无法正常工作。
package com.company;
import javax.swing.*;
public class BMI_Calculator() {
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField jt1 = new JTextFeild(30);
JButton jb = new JButton("Click here for BMI value");
enter code here
enter private BMI_Calculator() {
setTitle("BMI_Calculator");
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jp.add(jt1);
jt1.addActionListener(e -> {
int Height_input = jt1.getHeight();
jl.setText("Your height + 1 " + Get_BMI(Height_input));
});
jp.add(jb);
jb.addActionListener(e -> {
int input = jt1.getHeight();
jl.setText("Your height + 1 " + Get_BMI(input));
})
jp.add(jl);
add(jp);
}
private static int Get_BMI(int height) {
// adds one to height.
int sum = 1;
sum += height;
return sum;
}
public static void main(String[] args) {
new BMI_Calculator();
}
}
因此,当我运行它时会显示 textfeild 并显示按钮,问题是当我运行它时,例如,如果我在 textfeild 中输入 23,我会返回,“你的身高 + 1 是 21。” 发生了什么,它给了我这样的响应,就像我的 Get_BMI 方法应该获取高度并为其添加一个,但它没有这样做。即使我只是点击按钮而不在文本字段中输入任何数字,我也会得到“你的身高 + 是 21”。请帮助正确添加整数。谢谢。