[英]How can I use the same Event Handlers Performing same functions on multiple Objects of the same Kind in GWT (or Java AWT Swing)
我剛剛開始研究Gwt2.0。 我在這里有兩個文本框。 兩者都執行相同的事件操作。 使用
addFocusListener()
我現在所擁有的是。
areaBox.addFocusListener(new FocusListener(){
@Override
@Deprecated
public void onFocus(Widget arg0) {
// TODO Auto-generated method stub
areaBox.setTitle("Area");
}
@Override
public void onLostFocus(Widget arg0) {
if(areaBox.getText().length() >= 4 )
{
areaBox.setStyleName("gwt-TextBox-Success");
}
else
{
areaBox.setStyleName("gwt-TextBox-Error");
cityBox.setText("Enter Area Name ");
areaBox.addFocusListener(new FocusListener(){
@Override
@Deprecated
public void onFocus(Widget arg0) {
areaBox.setText(null);
areaBox.setStyleName("gwt-TextBox-AE");
}
@Override
@Deprecated
public void onLostFocus(Widget arg0) {
}
});
}
}
});
cityBox.addFocusListener(new FocusListener(){
@Override
@Deprecated
public void onFocus(Widget arg0) {
cityBox.setTitle("City");
}
@Override
public void onLostFocus(Widget arg0) {
if(cityBox.getText().length() >= 4 )
{
cityBox.setStyleName("gwt-TextBox-Success");
}
else
{
cityBox.setStyleName("gwt-TextBox-Error");
cityBox.setText("Enter City Name ");
cityBox.addFocusListener(new FocusListener(){
@Override
@Deprecated
public void onFocus(Widget arg0) {
cityBox.setText(null);
cityBox.setStyleName("gwt-TextBox-AE");
}
@Override
@Deprecated
public void onLostFocus(Widget arg0) {
// TODO Auto-generated method stub
}
});
}
}
});
該代碼的作用是。 當聚焦於區域文本框時,將顯示一個工具提示,顯示要輸入的內容。 當焦點丟失或進入下一個文本框(例如,城市文本框)時,它將檢查輸入的字符串是否大於4個字符。 如果是,則將SUCCESS CSS樣式應用於該框,如果不是ERROR,則應用CSS樣式。 因此,再次單擊它(AreaBox)時,將清除文本並重置css樣式。
上面是2個文本框之間的示例。 請幫助我,我有將近10個這樣的字段,我想最小化代碼。 我正在考慮使用集合或自定義窗口小部件。 但是不知道從哪里開始。 需要您的幫助和意見。 謝謝...
這是我如何解決此問題的方法:
areaBox.addFocusListener(generateFocusListener("Area", "Enter Area Name "));
cityBox.addFocusListener(generateFocusListener("City", "Enter City Name "));
FocusListener generateFocusListener(final String title, final String text) {
return new FocusListener(){
@Override
@Deprecated
public void onFocus(Widget widget) {
// initial focus happens here
TextBox box = (TextBox) widget;
box.setTitle(title);
}
@Override
public void onLostFocus(Widget widget) {
// Focus is lost for the first time
TextBox box = (TextBox) widget;
if(box.getText().length() >= 4 )
{
box.setStyleName("gwt-TextBox-Success");
// Change focus listener so that now once pressed it resets
box.addFocusListener(new FocusListener(){
@Override
@Deprecated
public void onFocus(Widget widget) {
TextBox box = (TextBox) widget;
box.setText(null);
box.setStyleName("gwt-TextBox-AE");
}
@Override
@Deprecated
public void onLostFocus(Widget widget) {
TextBox box = (TextBox) widget;
if(box.getText().length() >= 4 )
{
box.setStyleName("gwt-TextBox-Success");
}
else
{
box.setStyleName("gwt-TextBox-Error");
box.setText(text);
}
}
});
}
else
{
box.setStyleName("gwt-TextBox-Error");
box.setText(text);
}
}
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.