英文:
How to specify a number input range in a controlP5 textField?
问题
如何在textField中阻止以逗号 "," 和数字 "0" 开头的输入?ControlP5 过滤器没有起作用。public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key >= 5 && key <= 25) e.setKeyChar(''); ... //x10.setText 如何在textField中限制数字输入范围
如何防止textField中以字符 "," 和 "0" 开头的输入。如果(points >= 5 && points <= 25) { 例如 ControlP5 库没有起作用。详见:http://www.sojamo.de/libraries/controlP5/reference/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 textField
How 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.
答案1
得分: 2
以下是您想要的代码部分:
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);
}
}
请注意,我已经将代码中的 HTML 转义字符解析为它们的原始字符。
英文:
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).
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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论