如何在 Jframe 中正确添加整数?


糖果
2025-03-17 08:37:04 (15天前)

我正在尝试用 Java制作一个BMI计算器。然而,首先我正在玩一些 Jframe 的东西,它似乎无法正常工作。

  1. package com.company;
  2. import javax.swing.*;
  3. public class BMI_Calculator() {
  4. JPanel jp = new JPanel();
  5. JLabel jl = new JLabel();
  6. JTextField jt1 = new JTextFeild(30);
  7. JButton jb = new JButton("Click here for BMI value");
  8. enter code here
  9. enter private BMI_Calculator() {
  10. setTitle("BMI_Calculator");
  11. setVisible(true);
  12. setSize(400, 300);
  13. setDefaultCloseOperation(EXIT_ON_CLOSE);
  14. jp.add(jt1);
  15. jt1.addActionListener(e -> {
  16. int Height_input = jt1.getHeight();
  17. jl.setText("Your height + 1 " + Get_BMI(Height_input));
  18. });
  19. jp.add(jb);
  20. jb.addActionListener(e -> {
  21. int input = jt1.getHeight();
  22. jl.setText("Your height + 1 " + Get_BMI(input));
  23. })
  24. jp.add(jl);
  25. add(jp);
  26. }
  27. private static int Get_BMI(int height) {
  28. // adds one to height.
  29. int sum = 1;
  30. sum += height;
  31. return sum;
  32. }
  33. public static void main(String[] args) {
  34. new BMI_Calculator();
  35. }
  36. }

因此,当我运行它时会显示 textfeild 并显示按钮,问题是当我运行它时,例如,如果我在 textfeild 中输入 23,我会返回,“你的身高 + 1 是 21。” 发生了什么,它给了我这样的响应,就像我的 Get_BMI 方法应该获取高度并为其添加一个,但它没有这样做。即使我只是点击按钮而不在文本字段中输入任何数字,我也会得到“你的身高 + 是 21”。请帮助正确添加整数。谢谢。

1 条回复
  1. 动动手指,沙发就是你的了!
登录 后才能参与评论