如何在 controlP5 文本字段中指定数字输入范围?
How to specify a number input range in a controlP5 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 <= 25) {例如 Controlp5 库不起作用。 http://www.sojamo.de/libraries/controlP5/reference/controlP5/Textfield.InputFilter.html.
下面的代码就是您想要的——将它放在 draw()
的末尾(而不是 keyPressed()
因为 keyPressed()
在 controlP5 使用按键事件之前被调用)。
但是,您的要求是有问题的。您希望在用户输入时验证数字,而不是在输入完全输入之后。这就导致了一个问题:假设他们想输入“15”;他们首先键入“1”,但这将被拒绝,因为它不在正确的范围 (5-25) 内。最好在完全输入后验证输入(例如,当按下回车键时),或者改用滑块或旋钮。
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);
}
}
具体来说,当文本字段中的第一个字符为 , 和 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 <= 25) {例如 Controlp5 库不起作用。 http://www.sojamo.de/libraries/controlP5/reference/controlP5/Textfield.InputFilter.html.
下面的代码就是您想要的——将它放在 draw()
的末尾(而不是 keyPressed()
因为 keyPressed()
在 controlP5 使用按键事件之前被调用)。
但是,您的要求是有问题的。您希望在用户输入时验证数字,而不是在输入完全输入之后。这就导致了一个问题:假设他们想输入“15”;他们首先键入“1”,但这将被拒绝,因为它不在正确的范围 (5-25) 内。最好在完全输入后验证输入(例如,当按下回车键时),或者改用滑块或旋钮。
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);
}
}