中指定数字输入范围

中指定数字输入范围

本文介绍了如何在 controlP5 textField 中指定数字输入范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具体来说,当 textField 中的第一个字符是 , 和 0 时,如何防止输入?controlP5 过滤器不起作用.public void keyPressed (KeyEvent e) { int key = e.getKeyCode();if (key => 5 && key <= 25) e.setKeyChar('' ...//x10.setText ? 如何在 textField 中制作数字输入范围如何防止输入第一个字符,"和0"在文本字段中.if (points> = 5 && points http://www.sojamo.de/libraries/controlP5/参考/controlP5/Textfield.InputFilter.html.

Specifically, how do I prevent input when the first character is , and 0 in a textField? The controlP5 filter did not work. public void keyPressed (KeyEvent e) { int key = e.getKeyCode(); if (key => 5 && key <= 25) e.setKeyChar('' ... //x10.setText ? How to make a number input range from in a textFieldHow to prevent input by the first character "," and "0" in textField. if (points> = 5 && points <= 25) {example the Controlp5 library did not work. http://www.sojamo.de/libraries/controlP5/reference/controlP5/Textfield.InputFilter.html.

推荐答案

下面的代码就是你想要的 -- 把它放在 draw() 的末尾(而不是 keyPressed() 因为 keyPressed() 在 controlP5 使用按键事件之前被调用.

The code below is what you want -- put it at the end of draw() (rather than keyPressed() because keyPressed() is called before controlP5 consumes the key event).

然而,你所要求的是有问题的.您希望在用户输入输入时验证数字,而不是在输入完全输入后验证.这导致了一个问题:假设他们希望输入15";他们首先输入1",但这将被拒绝,因为它不在正确的范围内(5-25).最好在完全输入后(例如按下回车键时)验证输入,或者改用滑块或旋钮.

However, what you're asking for is problematic. You want to validate the number as the user types in input, and not after the input is fully entered. This leads to a problem: suppose they wish to type in "15"; they first type "1", but this will be rejected because it is not within the correct range (5-25). It would be better to validate input after it is fully entered (when the enter key is pressed for example), or use slider or knob instead.

if (keyPressed && textField.isFocus()) {
    float n;
    try {
        n = Float.parseFloat(textField.getText().replace(',', '.')); // may throw exception
        if (!(n >= 5 && n <= 25)) {
            throw new NumberFormatException(); // throw to catch below
        }

    } catch (Exception e2) {
        String t;
        if (textField.getText().length() > 1) {
            t = textField.getText().substring(0, textField.getText().length() - 1);
        } else {
            t = "";
        }
        textField.setText(t);
    }
}

这篇关于如何在 controlP5 textField 中指定数字输入范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 16:45