JTextField 根据条件获取值

发布于 2024-12-29 11:32:56 字数 108 浏览 5 评论 0原文

我使用 JTextField 获取平均值。这意味着平均值必须从 0 到 100 开始。因此文本字段仅允许访问 0 到 100。如果我给出 101 意味着该值不会添加到文本字段中。如何设置这个问题的条件?

Am using JTextField for get average.It means the average must be start with 0 to 100.so the textfield allow to access the 0 to 100 only.If I give 101 means the value don't added in the textfield.how to set the condition for this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

沫雨熙 2025-01-05 11:32:56

使用 JSpinner 带有 SpinnerNumberModel 反而。

有关更多详细信息,请参阅如何使用 Spinners

Use a JSpinner with a SpinnerNumberModel instead.

See How to Use Spinners for more details.

短暂陪伴 2025-01-05 11:32:56

您必须使用 KeyListener 来进行验证。

例如,

final JTextField myTextField = new JTextField();
myTextField.addKeyListener(new KeyListener() {
      public void keyPressed(KeyEvent keyEvent) {

      }

      public void keyReleased(KeyEvent keyEvent) {
// Here write the comparison logic
                 if (Integer.parseInt(myTextField.getText()) > 100){
                     myTextField.setText(""); // Make it blank
                 }
      }

      public void keyTyped(KeyEvent keyEvent) {
      }
    });

您也可以使用 KeyAdapter。希望这有帮助。

You have to use KeyListener where you can do the validation.

For example

final JTextField myTextField = new JTextField();
myTextField.addKeyListener(new KeyListener() {
      public void keyPressed(KeyEvent keyEvent) {

      }

      public void keyReleased(KeyEvent keyEvent) {
// Here write the comparison logic
                 if (Integer.parseInt(myTextField.getText()) > 100){
                     myTextField.setText(""); // Make it blank
                 }
      }

      public void keyTyped(KeyEvent keyEvent) {
      }
    });

You can use KeyAdapter as well. Hope this helps.

悲念泪 2025-01-05 11:32:56

JTextField 中显示的可见数据是 java.lang.String 对象。

如果你想在其中放入数字类型(比如说浮点数),你必须做这样的事情:

JTextField tf=new JTextField();
float average=//get the average however you wish...

if( ( average <= 100 ) && ( average >= 0 ) )
tf.setText(String.valueOf(average));

这对我来说足够简单,但我想问更多关于你的编程背景的问题。这是与 JTextField 有关的问题,还是与实际情况有关的问题?

The visible data that is displayed in a JTextField is a java.lang.String object.

If you want to put a numeric type in it (let's say float), you have to do something like this:

JTextField tf=new JTextField();
float average=//get the average however you wish...

if( ( average <= 100 ) && ( average >= 0 ) )
tf.setText(String.valueOf(average));

this is trivial enough for me to want to ask more questions about your programming background though. Was this a question related to the JTextField, or was this about the actual condition?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文