java 如何将掩码设置为 SWT 文本以仅允许小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11831927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set a Mask to a SWT Text to only allow Decimals
提问by Josejulio
What I want is that the user can only input decimal numbers on a Text, I don't want it to allow text input as:
我想要的是用户只能在文本上输入十进制数字,我不希望它允许文本输入为:
- HELLO
- ABC.34
- 34.HEY
- 32.3333.123
- 你好
- ABC.34
- 34.嘿嘿
- 32.3333.123
I have been trying using VerifyListener, but it only gives me the portion of the text that got inserted, so I end up having the text that I want to insert and the text before the insertion, tried also combining the text, but I got problems when you delete a key (backspace) and I end up having a String like 234[BACKSPACE]455.
我一直在尝试使用VerifyListener,但它只给了我插入的文本部分,所以我最终得到了我想要插入的文本和插入前的文本,还尝试组合文本,但我遇到了问题当您删除一个键(退格键)时,我最终得到了一个像 234[BACKSPACE]455 这样的字符串。
Is there a way to set a Mask on a Text or successfully combine VerifyEvent with the current text to obtain the "new text" before setting it to the Text?
有没有办法在文本上设置掩码或成功地将验证事件与当前文本结合以在将其设置为文本之前获取“新文本”?
回答by Baz
You will have to add a Listener
on the Text
using SWT.Verify
. Within this Listener
you can verify that the input contains only a decimal number.
您必须Listener
在Text
using上添加一个SWT.Verify
。在此Listener
您可以验证输入是否仅包含十进制数。
The following will only allow the insertion of decimals into the text field. It will check the value each time you change something in the text and reject it, if it's not a decimal.
This will solve your problem, since the VerifyListener
is executed BEFORE the new text is inserted. The new text has to pass the listener to be accepted.
以下将只允许在文本字段中插入小数。每次更改文本中的某些内容时,它都会检查该值并拒绝它,如果它不是小数。这将解决您的问题,因为在VerifyListener
插入新文本之前执行。新文本必须通过侦听器才能被接受。
public static void main(String[] args) {
Display display = Display.getDefault();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Text textField = new Text(shell, SWT.BORDER);
textField.addVerifyListener(new VerifyListener() {
@Override
public void verifyText(VerifyEvent e) {
Text text = (Text)e.getSource();
// get old text and create new text by using the VerifyEvent.text
final String oldS = text.getText();
String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
boolean isFloat = true;
try
{
Float.parseFloat(newS);
}
catch(NumberFormatException ex)
{
isFloat = false;
}
System.out.println(newS);
if(!isFloat)
e.doit = false;
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
回答by Tom Seidel
Have you tried the FormattedText Widgets from Nebula? - They are an easy way to implement these kind of input fields, see http://eclipse.org/nebula/widgets/formattedtext/formattedtext.php
您是否尝试过 Nebula 的 FormattedText 小部件?- 它们是实现此类输入字段的简单方法,请参阅http://eclipse.org/nebula/widgets/formattedtext/formattedtext.php
回答by Stefan
In order to get the behavior that I wanted I had to use several listeners:
为了获得我想要的行为,我不得不使用几个监听器:
- A VerifyListner restricts the characters that are accepted as partial input while typing
- A FocusListener validates the total input when leaving focus. If the total input is not valid, an error decoration will be shown.
A ModifyListener checks if the error decoration can be hidden while typing. It does not show the error decoration since invalid partial input like "4e-" is allowed to finally enter "4e-3"
valueField.addVerifyListener((event) -> restrictInput(event)); valueField.addModifyListener((event) -> validateValueOnChange(valueField.getText())); valueField.addFocusListener(new FocusListener() { @Override public void focusGained(org.eclipse.swt.events.FocusEvent e) {} @Override public void focusLost(org.eclipse.swt.events.FocusEvent event) { validateValueOnFocusLoss(valueField.getText()); } }); protected void restrictInput(VerifyEvent event) { String allowedCharacters = "0123456789.,eE+-"; String text = event.text; for (int index = 0; index < text.length(); index++) { char character = text.charAt(index); boolean isAllowed = allowedCharacters.indexOf(character) > -1; if (!isAllowed) { event.doit = false; return; } } } protected void validateValueOnChange(String text) { try { Double.parseDouble(valueField.getText()); valueErrorDecorator.hide(); } catch (NumberFormatException exception) { //expressions like "5e-" are allowed while typing } } protected void validateValueOnFocusLoss(String value) { try { Double.parseDouble(valueField.getText()); valueErrorDecorator.hide(); } catch (NumberFormatException exception) { valueErrorDecorator.show(); } }
- VerifyListner 限制在键入时作为部分输入接受的字符
- FocusListener 在离开焦点时验证总输入。如果总输入无效,将显示错误修饰。
ModifyListener 检查是否可以在键入时隐藏错误修饰。它不显示错误修饰,因为像“4e-”这样的无效部分输入被允许最终输入“4e-3”
valueField.addVerifyListener((event) -> restrictInput(event)); valueField.addModifyListener((event) -> validateValueOnChange(valueField.getText())); valueField.addFocusListener(new FocusListener() { @Override public void focusGained(org.eclipse.swt.events.FocusEvent e) {} @Override public void focusLost(org.eclipse.swt.events.FocusEvent event) { validateValueOnFocusLoss(valueField.getText()); } }); protected void restrictInput(VerifyEvent event) { String allowedCharacters = "0123456789.,eE+-"; String text = event.text; for (int index = 0; index < text.length(); index++) { char character = text.charAt(index); boolean isAllowed = allowedCharacters.indexOf(character) > -1; if (!isAllowed) { event.doit = false; return; } } } protected void validateValueOnChange(String text) { try { Double.parseDouble(valueField.getText()); valueErrorDecorator.hide(); } catch (NumberFormatException exception) { //expressions like "5e-" are allowed while typing } } protected void validateValueOnFocusLoss(String value) { try { Double.parseDouble(valueField.getText()); valueErrorDecorator.hide(); } catch (NumberFormatException exception) { valueErrorDecorator.show(); } }
The ModifyListener could be further improved to check for partial input that is not able to finally give a valid total input, e.g. "4e-....3". In that special case the ModifyListener should activate the error decoration while typing.
可以进一步改进 ModifyListener 以检查无法最终给出有效总输入的部分输入,例如“4e-....3”。在这种特殊情况下,ModifyListener 应该在键入时激活错误修饰。
回答by Naxos84
In addition to @Tom Seidel's answer:
You could use a org.eclipse.swt.widgets.Spinner
. This allows only digits. You can specify min and max value and the return value is an int
so no need to cast a String
.
除了@Tom Seidel 的回答:
您可以使用org.eclipse.swt.widgets.Spinner
. 这仅允许数字。您可以指定 min 和 max 值,返回值是 anint
所以不需要强制转换 a String
。
final Composite composite parent = new Composite(superParent, SWT.NONE);
parent.setLayout(new FillLayout());
final Spinner spinner = new Spinner(parent, SWT.BORDER);
spinner.setvalues(0, 10, Integer.MAX_VALUE, 0, 1, 10);
The value of the Spinner
can than be retrieved by calling:
然后Spinner
可以通过调用来检索的值:
int selectedValue = spinner.getSelection();