在eclipse-rcp / swt中创建多个相同的文本验证侦听器 [英] Creating multiple identical text verify listeners in eclipse-rcp/swt
问题描述
我正在尝试验证多个文本框的输入(即它们应该是一个数字),并在。
I'm trying to validate the input of multiple text boxes (i.e. they should be a number), and found the useful code snippet below here.
但是,如果我有三个文本框(文本
, moreText
和 evenMoreText
),如何对每个应用具有相同功能的验证侦听器,而不必重复( .addVerifyListener(new VerifyListener(){...
)代码三遍?
However, if I have three text boxes (text
, moreText
and evenMoreText
), how can I apply a verify listener with the same functionality to each, without having to repeat the (.addVerifyListener(new VerifyListener() {...
) code three times?
我不想实现switch语句或类似语句(决定哪个文本框以将其应用于),我想要更通用的东西(将来也许可以将其提供给其他类使用)。
I don't want to implement a switch statement or similar (to decide which text box to apply it to), I want something more generic (that I can perhaps make available for other classes to use in the future).
text.addVerifyListener(new VerifyListener() {
@Override
public void verifyText(VerifyEvent e) {
final String oldS = text.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try {
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
} catch (final NumberFormatException numberFormatException) {
// value is not decimal
e.doit = false;
}
}
});
推荐答案
定义 VerifyListener
并从 VerifyEvent
获取实际的文本
:
VerifyListener listener = new VerifyListener()
{
@Override
public void verifyText(VerifyEvent e)
{
// Get the source widget
Text source = (Text) e.getSource();
// Get the text
final String oldS = source.getText();
final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
try
{
BigDecimal bd = new BigDecimal(newS);
// value is decimal
// Test value range
}
catch (final NumberFormatException numberFormatException)
{
// value is not decimal
e.doit = false;
}
}
};
// Add listener to both texts
text.addVerifyListener(listener);
anotherText.addVerifyListener(listener);
如果您想在其他地方使用它好了,创建一个新类:
If you want to use it in other places as well, create a new class:
public class MyVerifyListener implements VerifyListener
{
// The above code in here
}
然后使用:
MyVerifyListener listener = new MyVerifyListener();
text.addVerifyListener(listener);
anotherText.addVerifyListener(listener);
这篇关于在eclipse-rcp / swt中创建多个相同的文本验证侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!