笔者使用的GWT2.3,它的弹窗控件(DiagBox)默认是不提供关闭按钮的,因此对其进行改造。
要进行改造,首先应认识到,GWT的每一个控件,对应的其实都是HTML的实现,GWT也支持我们拿到html元素,然后对其做修改,例如,对于窗体控件,可以通过geCaption()方法,拿到窗体头部对象,然后将其转为HTML对象,也就是
HTML caption = (HTML) getCaption()。拿到这个caption这个HTML对象之后,就能调用getElement().appenChild()方法,在上面添加其他元素,例如添加一个关闭的按钮。之后再给这个关闭按钮添加点击事件就OK啦~
具体实现如下
public class MyDialogBox extends DialogBox
{
private Label closeBtn;
private Label captiontLabel;
public MyDialogBox()
{
super();
this.createCaptionWithClose();
this.setModal(true);
this.setAutoHideOnHistoryEventsEnabled(true);
this.setAnimationEnabled(true);
this.setGlassEnabled(true);
}
private void createCaptionWithClose()
{
closeBtn = new Label("×");
closeBtn.setStylePrimaryName("close");
FlexTable captionLayoutTable = new FlexTable();
captionLayoutTable.setWidth("100%");
captiontLabel = new Label("");
captionLayoutTable.setWidget(0, 0, captiontLabel);
captionLayoutTable.setWidget(0, 1, closeBtn);
captionLayoutTable.getCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.HorizontalAlignmentConstant.endOf(HasDirection.Direction.LTR));
HTML caption = (HTML) getCaption();
caption.getElement().appendChild(captionLayoutTable.getElement());
caption.addClickHandler(new ClickHandler()
{
@Override
public void onClick(ClickEvent event)
{
EventTarget target = event.getNativeEvent().getEventTarget();
Element targetElement = (Element) target.cast();
if (targetElement == closeBtn.getElement())
{
closeBtn.fireEvent(event);
}
}
});
addCloseHandler(new ClickHandler()
{
@Override
public void onClick(ClickEvent event)
{
hide();
}
});
}
public void addCloseHandler(ClickHandler handler)
{
closeBtn.addClickHandler(handler);
}
}