Monday 5 September 2011

GWT Dialog Box With Close Button

Due to the internals of the GWT Dialog Box, extending it to add support for a close button can be a little tricky if you dont understand what your looking for. Alas below demonstrates adding an anchor to the caption area of the dialog, all that's left to do is for you to style the anchor. Happy GWT'ing.

Some people will moan that adding a library such as Smart GWT will add this functionality. Whilst true it also adds a boat load of library code you may never need. Keep compile times short and sweet and use the minimum amount necessary.

// Create anchor we want to accept click events
final Anchor myAnchor = new Anchor("My Anchor");

// Add handler to anchor
myAnchor.addClickHandler(new ClickHandler() {
  @Override
  public void onClick(ClickEvent event) {
    Window.alert("Anchor was clicked");
  }
});

// Create dialog
final DialogBox myDialog = new DialogBox();
myDialog.setText("My Dialog");

// Get caption element
final HTML caption = ((HTML)myDialog.getCaption());

// Add anchor to caption
caption.getElement().appendChild(myAnchor.getElement());

// Add click handler to caption
caption.addClickHandler(new ClickHandler() {
  @Override
  public void onClick(ClickEvent event) {
    // Get x,y caption click relative to the anchor
    final int x = event.getRelativeX(myAnchor.getElement());
    final int y = event.getRelativeY(myAnchor.getElement());

    // Check click was within bounds of anchor
    if(x >= 0 && y >= 0 && 
      x <= myAnchor.getOffsetWidth() && 
      y <= myAnchor.getOffsetHeight()) {
        // Raise event on anchor
        myAnchor.fireEvent(event);
    }
  }
});

// Show the dialog
myDialog.show();

No comments:

Post a Comment