我尝试验证多个文本框的输入(即它们应该是一个数字),并在here下面找到了有用的代码片段。
但是,如果我有三个文本框(text、moreText和evenMoreText),我如何才能对每个文本框应用具有相同功能的验证侦听器,而不必重复三次(.addVerifyListener(new VerifyListener() {...)代码?
我不想实现switch语句或类似的语句(决定将其应用于哪个文本框),我想要更通用的语句(也许我可以让其他类在将来使用它)。
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;
}
}
});发布于 2012-12-20 21:29:16
预先定义VerifyListener并从VerifyEvent获取实际的Text
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);如果您还想在其他地方使用它,请创建一个新类:
public class MyVerifyListener implements VerifyListener
{
// The above code in here
}然后使用:
MyVerifyListener listener = new MyVerifyListener();
text.addVerifyListener(listener);
anotherText.addVerifyListener(listener);https://stackoverflow.com/questions/13973133
复制相似问题