【发布时间】:2011-09-23 21:41:14
【问题描述】:
在 swt 中,文本小部件允许任何字符串。 但是在其中输入 Decimal 值的最合适的 SWT 小部件是什么?
我找到了两个答案:
- 首先,实现VerifyKeyListener和VerifyListener,适用于法语十进制,但简单易实现:
package test.actions;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.widgets.Text;
public final class AmountVerifyKeyListener implements VerifyListener, VerifyKeyListener {
private static final String REGEX = "^[-+]?[0-9]*[,]?[0-9]{0,2}+$";
private static final Pattern pattern = Pattern.compile(REGEX);
public void verifyText(VerifyEvent verifyevent) {
verify(verifyevent);
}
public void verifyKey(VerifyEvent verifyevent) {
verify(verifyevent);
}
private void verify (VerifyEvent e) {
String string = e.text;
char[] chars = new char[string.length()];
string.getChars(0, chars.length, chars, 0);
Text text = (Text)e.getSource();
if ( ( ",".equals(string) || ".".equals(string) ) && text.getText().indexOf(',') >= 0 ) {
e.doit = false;
return;
}
for (int i = 0; i < chars.length; i++) {
if (!(('0' <= chars[i] && chars[i] <= '9') || chars[i] == '.' || chars[i] == ',' || chars[i] == '-')) {
e.doit = false;
return;
}
if ( chars[i] == '.' ) {
chars[i] = ',';
}
}
e.text = new String(chars);
final String oldS = text.getText();
String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
Matcher matcher = pattern.matcher(newS);
if ( !matcher.matches() ) {
e.doit = false;
return;
}
}
}
以及与 verifyKeyListener 关联的主类:
package test.actions;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class TestMain {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(2, false));
final Text text = new Text(shell, SWT.NONE);
text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
text.addVerifyListener(new AmountVerifyKeyListener() ) ;
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
}
- 使用 nebula 项目中的 FormattedText:http://eclipse.org/nebula/
有人看到另一种解决方案吗?
【问题讨论】:
-
很遗憾 SWT 没有如此重要的小部件可用...我使用 Nebula 仅用于数字格式(我写了我的日期和时间)。我发现它非常好,但我必须编辑一些代码以使其与单元格编辑器一起使用并且不干扰数据绑定。
标签: java text swt eclipse-rcp decimal