我的问题是:
我希望 Eclipse RCP 中的文本字段仅允许键入数字作为输入,并且要求最多应允许“x”(假设 x=5)个字符。
我怎样才能在 RCP 中完成它?
我尝试过如下代码:
txtInput.addListener(SWT.Verify, new DecimalText(
txtInsuranceValue, 8, 1000.00));
其中 txtInput 是文本字段。但是当我在运行时重复输入该字段时,该监听器失败了。
请问还有其他选择吗?
最佳答案
这会将 Text 控件中的最大字符数设置为 5,并且只允许输入数字:
txtInput.setTextLimit(5);
txtInput.addVerifyListener(new VerifyListener() {
public void verifyText(VerifyEvent event) {
// Assume we allow it
event.doit = true;
String text = event.text;
char[] chars = text.toCharArray();
//Don't allow if text contains non-digit characters
for (int i = 0; i < chars.length; i++) {
if (!Character.isDigit(chars[i])) {
event.doit = false;
break;
}
}
}
});
编辑:我修改了我的答案,以允许用户还使用“setText(String string)”设置文本,同时仍然不允许非数字字符。
关于textbox - 如何使文本防止输入超过 'x' 位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6028370/