How to use gwtbootstrap3 calendar with UiBinder - gwt

Can we use gwtbootstrap3 fullcalendar mentioned at http://gwtbootstrap3.github.io/gwtbootstrap3-demo/#fullcalendar with UiBinder.
I am trying to use it with UiBinder and nothing is appearing on that page.
code to my UiBinder class
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui"
xmlns:b="urn:import:org.gwtbootstrap3.client.ui.gwt">
<g:HTMLPanel ui:field="calendarContainer">
</g:HTMLPanel>
</ui:UiBinder>
code to the corresponding view class
public class EventView extends ReverseCompositeView<IEventView.IEventPresenter> implements IEventView {
private static EventViewUiBinder uiBinder = GWT.create( EventViewUiBinder.class );
interface EventViewUiBinder extends UiBinder<Widget, EventView> {
}
#UiField
HTMLPanel calendarContainer;
#Override
public void createView() {
//don't create the view before to take advantage of the lazy loading mechanism
initializeCalendar();
initWidget( uiBinder.createAndBindUi( this ) );
}
private void initializeCalendar() {
final FullCalendar fc = new FullCalendar("event-calendar", ViewOption.month, true);
fc.addLoadHandler(new LoadHandler() {
#Override
public void onLoad(LoadEvent loadEvent) {
addEvents();
}
private void addEvents() {
for (int i = 0; i < 15; i++) {
Event calEvent = new Event("id "+ i, "this is event "+i);
int day = Random.nextInt(10);
Date start = new Date();
CalendarUtil.addDaysToDate(start, -1 * day);
calEvent.setStart(start);
if(i%3 ==0){
calEvent.setAllDay(true);
}else{
Date d = new Date(start.getTime());
d.setHours(d.getHours()+1);
calEvent.setEnd(d);
}
fc.addEvent(calEvent);
}
}
});
calendarContainer.add(fc);
}
}
and I am using mvp4g framework.

initializeCalendar();
initWidget( uiBinder.createAndBindUi( this ) );
You should first init the widget and then initialize the calendar. This is because you are adding your FullCalendar to the calendarContainer HTMLPanel in initializeCalendar. And before the call to initWidget, calendarContainer is null.
I think you can go a step further and do it like this:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui"
xmlns:b="urn:import:org.gwtbootstrap3.client.ui.gwt"
xmlns:f="urn:import:org.gwtbootstrap3.extras.fullcalendar">
<g:HTMLPanel>
<f:FullCalendar ui:field="fullCalendar" />
</g:HTMLPanel>
</ui:UiBinder>
And then in your EventView:
#UiField(provided = true) FullCalendar fullCalendar;
#UiField(provided = true) means it's up to you to initialize this widget before calling initWidget. So, in this case, the order:
initializeCalendar();
initWidget( uiBinder.createAndBindUi( this ) );
is OK. Additionally, you don't have to add the FullCalendar to any panel anymore - it's already added, you just have to initialize it.

Related

GWT 2.5.1: dynamic required field indicator

What would be a better approach for displaying a dynamic required field indicator (in my case, display a '*' next to the field IF it is empty, hide it if the user type something, display it again if the user clears the input field) ?
The indicator is called requiredFieldHighlight in the code below.
MyValueBoxEditorDecorator.java
public class MyValueBoxEditorDecorator<T> extends Composite implements HasEditorErrors<T>,
IsEditor<ValueBoxEditor<T>>
{
interface Binder extends UiBinder<Widget, MyValueBoxEditorDecorator<?>>
{
Binder BINDER = GWT.create(Binder.class);
}
#UiField
DivElement label;
#UiField
SimplePanel contents;
#UiField
DivElement requiredFieldHighlight;
#UiField
DivElement errorLabel;
private ValueBoxEditor<T> editor;
private ValueBoxBase<T> valueBox;
/**
* Constructs a ValueBoxEditorDecorator.
*/
#UiConstructor
public MyValueBoxEditorDecorator()
{
initWidget(Binder.BINDER.createAndBindUi(this));
}
public MyValueBoxEditorDecorator(int dummy)
{
this();
valueBox = (ValueBoxBase<T>) new TextBoxTest(requiredFieldHighlight);
this.editor = valueBox.asEditor();
valueBox.addValueChangeHandler(new ValueChangeHandler<T>()
{
#Override
public void onValueChange(ValueChangeEvent<T> event)
{
MyValueBoxEditorDecorator.this.onValueChange();
}
});
contents.add(valueBox);
MyValueBoxEditorDecorator.this.onValueChange();
}
private void onValueChange()
{
T value = editor.getValue();
if (value == null)
{
requiredFieldHighlight.getStyle().setDisplay(Style.Display.INLINE_BLOCK);
return;
}
else
{
requiredFieldHighlight.getStyle().setDisplay(Style.Display.NONE);
}
}
public ValueBoxEditor<T> asEditor()
{
return editor;
}
public void setEditor(ValueBoxEditor<T> editor)
{
this.editor = editor;
}
#UiChild(limit = 1, tagname = "valuebox")
public void setValueBox(ValueBoxBase<T> widget)
{
contents.add(widget);
setEditor(widget.asEditor());
}
#Override
public void showErrors(List<EditorError> errors)
{
// this manages the content of my errorLabel UiField
}
}
UiBinder file:
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
xmlns:g='urn:import:com.google.gwt.user.client.ui'>
<ui:style src="common.css" />
<g:HTMLPanel width="100%">
<div ui:field="label" class="{style.label}"/>
<g:SimplePanel ui:field="contents" stylePrimaryName="{style.contents}" />
<div class="{style.errorLabel}" ui:field="errorLabel" />
<div class="{style.errorLabel} {style.requiredFieldHighlight}" ui:field="requiredFieldHighlight">*</div>
</g:HTMLPanel>
</ui:UiBinder>
The issue with my approach is that onValueChange() will not be called when my screen is initialized (before the user interacts with this widget), although I need the MyValueBoxEditorDecorator to update the status of its 'requiredFieldHighlight' !
This is why I created that TextBoxTest class. I simply pass it a reference to the indicator DivElement object and overload setText+setValue.
TextBoxTest.java
public class TextBoxTest extends TextBox
{
#Override
public void setText(String text)
{
super.setText(text);
updateRequiredFieldHighlight(text);
}
private final DivElement requiredFieldHighlight;
public TextBoxTest(DivElement requiredFieldHighlight)
{
super();
this.requiredFieldHighlight = requiredFieldHighlight;
}
private void updateRequiredFieldHighlight(String withValue)
{
if (withValue != null && !withValue.isEmpty())
{
requiredFieldHighlight.getStyle().setDisplay(Style.Display.NONE);
}
else
{
requiredFieldHighlight.getStyle().setDisplay(Style.Display.INLINE_BLOCK);
}
}
#Override
public void setValue(String value, boolean fireEvents)
{
super.setValue(value, fireEvents);
updateRequiredFieldHighlight(value);
}
}
I have several problems with that approach. First, it creates a dependency to another specific class of mine (TextBoxTest), and second, it does not really work properly because setText() is not automagically called by GWT when I clear the contents of the text field using the GUI ! In other words for the indicator to work properly, I need BOTH to overload setText+setValue in the TextBoxTest class and have to ValueChangeHandler added to my MyValueBoxEditorDecorator object. Why ? (and where would be the right event / place to handle a text change ?)
20150629 update: actually setValue() IS called when my screen is initialized. My valueChangeHandler is not triggered, 'though, due to GWT internals (I think due to setValue() provided without a fireEvents flag calling fireEvents overload with a False fireEvent flag).

How to add form elements in gwt-bootstrap3

I am trying to add some elements in gwt-bootstrap3 modal [link], I am using UI-binder to generate the screen but nothing is appear.
my ui binder class
<?xml version="1.0" encoding="UTF-8"?>
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder' xmlns:g='urn:import:com.google.gwt.user.client.ui' xmlns:b='urn:import:org.gwtbootstrap3.client.ui'
xmlns:res="urn:with:com.db.cary.client.resources.CSSResources">
<ui:with type="com.db.cary.client.resources.CSSResources" field="res">
</ui:with>
<b:Modal closable="true" fade="true" dataBackdrop="TRUE" dataKeyboard="true">
<b:ModalBody>
<b:Form type="HORIZONTAL">
<b:FieldSet>
<b:Legend>Please enter the book detail</b:Legend>
<b:FormGroup>
<b:FormLabel for="bookTitle" addStyleNames="col-lg-2">Title</b:FormLabel>
<g:FlowPanel addStyleNames="col-lg-10">
<b:TextBox placeholder="Enter book Title" ui:field="titleTextBox" />
</g:FlowPanel>
</b:FormGroup>
<b:FormGroup>
<b:FormLabel for="bookAuthor" addStyleNames="col-lg-2">Author</b:FormLabel>
<g:FlowPanel addStyleNames="col-lg-10">
<b:ListBox ui:field="authorListBox" />
<b:Button ui:field="newAuthorButton" type="LINK" size="EXTRA_SMALL">New author</b:Button>
</g:FlowPanel>
<g:FlowPanel addStyleNames="col-lg-offset-2 col-lg-10">
<b:TextBox ui:field="authorTextBox" placeholder="enter slash (/) separated list of authors"></b:TextBox>
</g:FlowPanel>
</b:FormGroup>
<b:FormGroup>
<b:FormLabel for="bookCategory" addStyleNames="col-lg-2">Category</b:FormLabel>
<g:FlowPanel addStyleNames="col-lg-10">
<b:ListBox ui:field="categoryListBox" />
<b:Button ui:field="newCategoryButton" type="LINK" size="EXTRA_SMALL">New Category</b:Button>
</g:FlowPanel>
<g:FlowPanel addStyleNames="col-lg-offset-2 col-lg-10">
<b:TextBox ui:field="categoryTextBox" placeholder="enter category"></b:TextBox>
</g:FlowPanel>
</b:FormGroup>
</b:FieldSet>
</b:Form>
</b:ModalBody>
<b:ModalFooter>
<b:Button type="PRIMARY" ui:field='submitButton'>Submit</b:Button>
<b:Button ui:field='cancelButton'>Cancel</b:Button>
</b:ModalFooter>
</b:Modal>
</ui:UiBinder>
and my view class
public class AddBook extends Modal {
interface CheckOutPopUpBinder extends UiBinder<Widget, AddBook> {
}
private static final CheckOutPopUpBinder binder = GWT.create(CheckOutPopUpBinder.class);
private final AuthorAndCategoryServiceAsync authorService = GWT.create(AuthorAndCategoryService.class);
private final LibraryServiceAsync libraryServiceAsync = GWT.create(LibraryService.class);
#UiField
TextBox titleTextBox;
#UiField
ListBox authorListBox;
#UiField
TextBox authorTextBox;
#UiField
ListBox categoryListBox;
#UiField
Button submitButton;
#UiField
Button cancelButton;
#UiField
Button newAuthorButton;
#UiField
Button newCategoryButton;
#UiField
TextBox categoryTextBox;
public AddBook(String title) {
binder.createAndBindUi(this);
setTitle(title);
initializeAuthorListBox();
initializeCategoryListBox();
}
private void initializeCategoryListBox() {
authorService.getCategories(null, new AsyncCallback<List<CategoryDTO>>() {
#Override
public void onFailure(Throwable arg0) {
Window.alert("unable to fetch category list");
}
#Override
public void onSuccess(List<CategoryDTO> arg0) {
for (CategoryDTO category : arg0)
categoryListBox.addItem(category.getCategoryName());
}
});
categoryListBox.setMultipleSelect(false);
categoryTextBox.setVisible(false);
}
private void initializeAuthorListBox() {
authorService.getAuthors(null, new AsyncCallback<List<AuthorDTO>>() {
#Override
public void onSuccess(List<AuthorDTO> arg0) {
for (AuthorDTO author : arg0) {
authorListBox.addItem(author.getAuthorName());
}
}
#Override
public void onFailure(Throwable arg0) {
Window.alert("Unable to fetch the list of authors");
}
});
authorListBox.setMultipleSelect(true);
authorTextBox.setVisible(false);
}
#UiHandler("cancelButton")
public void cancelAction(ClickEvent e) {
AddBook.this.hide();
}
#UiHandler("submitButton")
public void submitAction(ClickEvent e) {
AddBookDTO bookDTO = new AddBookDTO();
String bookTitle = titleTextBox.getText();
String bookCategory = categoryListBox.getSelectedValue() == null ? categoryTextBox.getText() : categoryListBox.getSelectedValue();
List<String> authorsList = new ArrayList<String>();
for (int i = 0; i < authorListBox.getItemCount(); i++) {
if (authorListBox.isItemSelected(i)) {
authorsList.add(authorListBox.getItemText(i));
}
}
if (null != authorTextBox.getText() && authorTextBox.getText().trim().length() > 0) {
String[] values = authorTextBox.getText().split("/");
for (String str : values) {
authorsList.add(str);
}
}
if (bookTitle == null || bookTitle.length() <= 0) {
Window.alert("Please enter a valid book title");
return;
} else if (bookCategory == null || bookCategory.length() <= 0) {
Window.alert("Please enter a valid book category");
return;
} else if (authorsList == null || authorsList.size() == 0) {
Window.alert("Please enter valid authors");
return;
}
bookDTO.setBookTitle(bookTitle);
bookDTO.setCategroyName(bookCategory);
bookDTO.setAuthors(authorsList);
libraryServiceAsync.addBook(bookDTO, new AsyncCallback<Boolean>() {
#Override
public void onFailure(Throwable arg0) {
Window.alert("There is some issue with database while adding book, Please contact your admin");
}
#Override
public void onSuccess(Boolean arg0) {
Window.alert("Book is successfully added !!!");
}
});
this.hide();
}
#UiHandler("newAuthorButton")
public void addAuthor(ClickEvent e) {
authorTextBox.setVisible(true);
}
#UiHandler("newCategoryButton")
public void addCategory(ClickEvent e) {
categoryTextBox.setVisible(true);
}
}
I am not sure, What is wrong but only header is appearing in the modal.
You are calling AddBook.this.show(); - this shows the Modal that is the base of this AddBook instance, not the instance defined in your UiBinder template. When you call setTitle(title); you are setting the header/title on this instance - this is why all you see is the header and not the rest of the modal. You should assign an ui:field to your Modal defined in your UiBinder template and show/hide it.
Also AddBook shouldn't be extending Modal - it shouldn't extend any widget class at all :) Normally, UiBinder classes are extending Composite - because your UiBinder template is composed of a variety of widgets and Composite is used to bring them together without exposing any of their APIs: you call initWidget with the result of binder.createAndBindUi(this).
But if you are creating a widget whose "main" widget is Modal, like here, you should just call binder.createAndBindUi(this) and ignore the Widget that is returned (just like you are doing now). This is because Modal attaches itself to the DOM, bypassing any GWT mechanism (actually, it conflicts with it).

Change span element style for GWT Cell using UiRenderer

How do I change the style for a Span HTML element when using UiRenderer with GWT 2.5?
I have setup a simple cell to be used in a CellTable. The ui.xml looks like this :
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder">
<ui:with field='stkval' type='java.lang.String'/>
<ui:with field='stkchg' type='java.lang.String'/>
<ui:with field='res' type='com.mycompanyclient.client.Enres'/>
<div id="parent">
<span><ui:text from='{stkval}'/></span>.
[<span class="{res.newstyle.positive}" ui:field="signSpan">
<ui:text from='{stkchg}'/>
</span>]
</div>
</ui:UiBinder>
Now when this cell is instantiated by the CellTable, I expect to change the class name of the signSpan to be changed based on the value passed into the render function. My java code looks something like this:
public class IndCell extends AbstractCell<QuoteProxy> {
#UiField
SpanElement signSpan;
#UiField(provided=true)
Enres res = Enres.INSTANCE;
interface MyUiRenderer extends UiRenderer {
SpanElement getSignSpan(Element parent);
void render(SafeHtmlBuilder sb, String stkval,String stkchg);
}
private static MyUiRenderer renderer = GWT.create(MyUiRenderer.class);
public IndCell() {
res.newstyle().ensureInjected();
}
#Override
public void render(com.google.gwt.cell.client.Cell.Context context,
QuoteProxy value, SafeHtmlBuilder sb) {
if (value.getChangeSign().contentequals('d')) {
renderer.getSignSpan(/* ?? */).removeClassName(res.newstyle().negative());
renderer.getSignSpan(/* ?? */).addClassName(res.newstyle().positive());
}
renderer.render(sb, value.getAmount(),value.getChange());
}
If I try to use the UiField directly it is set to Null. That makes sense because I am not calling the createandbindui function like I would for UiBinder. The renderer.getSignSpan looks promising but I dont know what to pass for parent.
All the example I could find use a event to identify the parent. But I dont want to click the cell generated.
Is there a way of changing style in the render method?
Because the class of the element is not a constant, you'll want to pass it as an argument to the render method so the cell's render reads:
public void render(Cell.Context context, QuoteProxy value, SafeHtmlBuilder sb) {
renderer.render(sb, value.getAmount(), value.getChange(),
value.getChangeSign().contentequals('d') ? res.newstyle.positive() : res.newstyle.negative());
}
I just thought that I would provide an example solution for those that are still struggling with this. In the case where you want to set the style prior to rendering, like in the case of rendering a positive value as "green" and a negative value as "red", you would do the following:
This would be your cell class:
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiRenderer;
public class ExpenseInfoCell extends AbstractCell<YourClassProxy> {
interface ExpenseInfoCellUiRenderer extends UiRenderer {
void render(SafeHtmlBuilder sb, String cost, String newStyle);
ValueStyle getCostStyle();
}
private static ExpenseInfoCellUiRenderer renderer = GWT
.create(ExpenseInfoCellUiRenderer.class);
#Override
public void render(Context context, YourClassProxy value, SafeHtmlBuilder sb) {
String coloredStyle = (value.getCost() < 0) ? renderer.getCostStyle()
.red() : renderer.getCostStyle().green();
renderer.render(sb, value.getCost()),
coloredStyle);
}
}
And this would be the accompanying UiBinder xml file
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder">
<ui:style field="costStyle" type="com.myproject.client.tables.MyValueStyle">
.red {
color: red;
}
.green {
color: green;
}
</ui:style>
<ui:with type="java.lang.String" field="cost" />
<ui:with type="java.lang.String" field="newStyle" />
<div>
<span class='{newStyle}'>
<ui:text from='{cost}' />
</span>
</div>
</ui:UiBinder>
Also, note that the field="costStyle" matches the getter in the class "getCostStyle". You must follow this naming convention otherwise the renderer will throw an error.

Horizontal scrollPanel not displaying with CellTree

I have a Celltree inside a ScrollPanel. I set the size of the ScrollPanel in the UIBinder as follow
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui">
<g:ScrollPanel ui:field="panel" width="240px" height="1200px"></g:ScrollPanel>
</ui:UiBinder>
In my Java class, I have the Following :
#UiField ScrollPanel panel;
public Arborescence() {
initWidget(uiBinder.createAndBindUi(this));
// Create a model for the tree.
TreeViewModel model = new CustomTreeModel();
/*
* Create the tree using the model. We specify the default value of the
* hidden root node as "Item 1".
*/
CellTree tree = new CellTree(model, "Item 1");
panel.add(tree);
}
My problem is when I populate the CellTree, the Horizontal bar is not displaying, even the content is overflowing. The Vertical bar is displaying fine.
Thanks
Update
Using FireBug, I see that the problem comes from element.style {
overflow: hidden;
}
It seems that it's an inline CSS that Override my CSS. Is there any way to change it ?
The LIENMAN78's solution is a little bit complicated. Well...After hours of searching, I found a simple solution : Wrapping the CellTree into a HorizontalPanel (or VerticalPanel) and then add it to the ScrollPanel
Here is the CellTree.ui.XML
<g:ScrollPanel width="100%" height ="1200px">
<g:HorizontalPanel ui:field="panel">
</g:HorizontalPanel>
</g:ScrollPanel>
And the relevant part of CellTree.java
...
#UiField HorizontalPanel panel;
...
panel.add(cellTree)
It's not the prettiest solution, but here is a quick fix.
/* fix horizontal scroll issue */
.cellTreeWidget>div,
.cellTreeWidget>div>div>div>div>div,
.cellTreeWidget>div>div>div>div>div>div>div>div>div
{
overflow: visible !important;
}
You can keep .cellTreeWidget as is if you are overriding CellTree.Style, but if you want to just do it quick and dirty change it to whatever the style name you added to the CellTree.
You can do this just once and do a replace-with in your module xml so that when CellTree calls GWT.create(Resource.class) internally it automatically gets replaced by a version with your fix.
<replace-with class="com.foo.common.client.gwt.laf.resource.CellTreeResources">
<when-type-is class="com.google.gwt.user.cellview.client.CellTree.Resources" />
</replace-with>
public class CellTreeResources implements CellTree.Resources
{
#Override
public ImageResource cellTreeClosedItem()
{
return CellBrowserResourcesImpl.INSTANCE.cellTreeClosedItem();
}
#Override
public ImageResource cellTreeLoading()
{
return LoadingResource.INSTANCE.loadingBar();
}
#Override
public ImageResource cellTreeOpenItem()
{
return CellBrowserResourcesImpl.INSTANCE.cellTreeOpenItem();
}
#Override
public ImageResource cellTreeSelectedBackground()
{
return CellBrowserResourcesImpl.INSTANCE.cellTreeSelectedBackground();
}
#Override
public Style cellTreeStyle()
{
return CellBrowserResourcesImpl.INSTANCE.cellTreeStyle();
}
public interface CellBrowserResourcesImpl extends CellTree.Resources
{
static final CellBrowserResourcesImpl INSTANCE = GWT.create(CellBrowserResourcesImpl.class);
#Override
#Source({ CellTree.Style.DEFAULT_CSS, "cellTree.css" })
Style cellTreeStyle();
}
}

GWT Close button in title bar of DialogBox

Is there a non JSNI way to add a close button to the title bar area of a DialogBox?
We used GWT-ext from the begining in our project. It was a bad idea. They have lots of cool widgets, but they are not GWT widgets AND they have no compatibility with GWT widgets. Once you choose GWT-Ext, everything, even the event mechanism, must be in the GWT-Ext way, not in the GWT way. This library will not be updated for the newest version of GWT, because the javascript library Ext is no more free. We are removing GWT-Ext from our project now.
It´s not possible to add a different widget int the GWT DialogBox caption, but you can extend "DecoratedPanel" (it is the DialogBox parent). Look at the DialogBox source to learn the techniques, specially how it adds the Caption object to the panel and how the window drag is implemented.
That´s what we have done here, and it works very well. We´ve made our own Caption class that extends FocusablePanel (a SimplePanel that captures all mouse events) and we added a HorizontalPanel to it, with buttons and text. We had to override onAttach() and onDetach() just by calling the super method (they are protected).
I believe I am not allowed to put our source code in here, so I just can give you these tips.
You can do it by adding a button to the center panel of the DialogBox:
Image closeButton = new Image("");
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
registerBox.hide();
}
});
closeButton.setStyleName("TopRight");
Then position it with CSS:
.TopRight {
float:right;
margin-top:-22px;
width:16px;
height:16px;
display:block;
background-image: url(images/cancel_16.png);
}
I created this caption class:
public class DialogBoxCaptionWithCancel extends Composite
implements Caption, HasClickHandlers {
#UiField
HTMLPanel mainPanel;
#UiField
HTML captionLabel;
#UiField
PushButton cancelButton;
private HandlerManager handlerManager = null;
private static final Binder binder = GWT.create(Binder.class);
interface Binder extends UiBinder<Widget, DialogBoxCaptionWithCancel> {
}
public DialogBoxCaptionWithCancel() {
initWidget(binder.createAndBindUi(this));
mainPanel.setStyleName("Caption");
Image upImage = new Image("images/closeWindow.png");
Image hoverImage = new Image("images/closeWindowFocus.png");
cancelButton.getUpFace().setImage(upImage);
cancelButton.getUpHoveringFace().setImage(hoverImage);
cancelButton.setStylePrimaryName("none");
}
/*
* (non-Javadoc)
*
* #see com.google.gwt.user.client.ui.Widget#onLoad()
*/
#Override
protected void onLoad() {
super.onLoad();
handlerManager = new HandlerManager(this);
}
#UiHandler("cancelButton")
public void cancelButtonOnClick(ClickEvent event) {
handlerManager.fireEvent(event);
}
#Override
public HandlerRegistration addMouseDownHandler(MouseDownHandler handler) {
return handlerManager.addHandler(MouseDownEvent.getType(), handler);
}
#Override
public HandlerRegistration addMouseUpHandler(MouseUpHandler handler) {
return handlerManager.addHandler(MouseUpEvent.getType(), handler);
}
#Override
public HandlerRegistration addMouseOutHandler(MouseOutHandler handler) {
return handlerManager.addHandler(MouseOutEvent.getType(), handler);
}
#Override
public HandlerRegistration addMouseOverHandler(MouseOverHandler handler) {
return handlerManager.addHandler(MouseOverEvent.getType(), handler);
}
#Override
public HandlerRegistration addMouseMoveHandler(MouseMoveHandler handler) {
return handlerManager.addHandler(MouseMoveEvent.getType(), handler);
}
#Override
public HandlerRegistration addMouseWheelHandler(MouseWheelHandler handler) {
return handlerManager.addHandler(MouseWheelEvent.getType(), handler);
}
#Override
public String getHTML() {
return "";
}
#Override
public void setHTML(String html) {
}
#Override
public String getText() {
return this.captionLabel.getText();
}
#Override
public void setText(String text) {
this.captionLabel.setText(text);
}
#Override
public void setHTML(SafeHtml html) {
}
#Override
public HandlerRegistration addClickHandler(ClickHandler handler) {
return handlerManager.addHandler(ClickEvent.getType(), handler);
}
}
The images are just captured from the behavior of IE8 when you mouse over the cancel button.
Here is the UiBinder code:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder
xmlns:ui='urn:ui:com.google.gwt.uibinder'
xmlns:g='urn:import:com.google.gwt.user.client.ui'>
<ui:style>
.htmlField {
width: 100%;
}
.pushButton {
border: none;
padding: 0px;
width: 49px;
height: 21px;
}
</ui:style>
<g:HTMLPanel ui:field="mainPanel">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td width="100%">
<g:HTML ui:field="captionLabel" addStyleNames="{style.htmlField}"></g:HTML>
</td>
<td>
<g:PushButton ui:field="cancelButton" addStyleNames="{style.pushButton}"></g:PushButton>
</td>
</tr>
</table>
</g:HTMLPanel>
</ui:UiBinder>
Then my class that extends DialogBox has the following:
public class MyDialogBox extends DialogBox implements ClickHandler {
...
// instantiate the caption with the cancel button
private static DialogBoxCaptionWithCancel caption = new DialogBoxCaptionWithCancel();
...
public MyDialogBox() {
// construct the dialog box with the custom caption
super(false, false, caption);
setWidget(binder.createAndBindUi(this));
// set the caption's text
caption.setText("My Caption");
}
....
protected void onLoad() {
super.onLoad();
// let us react to the captions cancel button
caption.addClickHandler(this);
}
...
#Override
public void onClick(ClickEvent event) {
// the caption's cancel button was clicked
this.hide();
}
A more simplier solution is to use gwt-ext (http://code.google.com/p/gwt-ext/). It is free and easy to use and integrate.
You can see their showcase http://www.gwt-ext.com/demo/.
I think that what you want is the MessageBox or Layout Window (they are on the Windows category of the showcase).
Regards.
You can try this out, slightly improved solution by fungus1487:
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.HasDirection;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.*;
/**
* #author Andrey Talnikov
*/
public class ClosablePopup extends DialogBox {
private Anchor closeAnchor;
/**
* Instantiates new closable popup.
*
* #param title the title
* #param defaultClose it {#code true}, hide popup on 'x' click
*/
public ClosablePopup(String title, boolean defaultClose) {
super(true);
closeAnchor = new Anchor("x");
FlexTable captionLayoutTable = new FlexTable();
captionLayoutTable.setWidth("100%");
captionLayoutTable.setText(0, 0, title);
captionLayoutTable.setWidget(0, 1, closeAnchor);
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 == closeAnchor.getElement()) {
closeAnchor.fireEvent(event);
}
}
});
if (defaultClose) {
addCloseHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
hide();
}
});
}
}
public void addCloseHandler(ClickHandler handler) {
closeAnchor.addClickHandler(handler);
}
}
Yes there is
No there isn't - at least not without fiddling with GWT's DialogBox class itself or by recreating the DialogBox using common widgets. This is a known issue in GWT, aka issue 1405 (Star it to show your interest).
However; DialogBox doesn't give us the tools to do this so we need to extend it - Edit: this doesn't work.
If you want to make a drop-in replacement for DialogBox you can name your class DialogBox and import it instead of the one that's included in GWT. This thread on the GWT forum gives better details on how this can be done (outdated, uses listeners) Outdated, the internals of DialogBox have been changed a lot since this thread - it doesn't work.
Here's some code I hacked to get the same results (used the linked thread for guidance). This doesn't work:
MyDialogBox:
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
public class MyDialogBox extends DialogBox {
private class crossHandler implements ClickHandler, MouseOverHandler, MouseOutHandler
{
#Override
public void onClick(ClickEvent event) {
hide();
Window.alert("Click!");
}
#Override
public void onMouseOver(MouseOverEvent event) {
DOM.setStyleAttribute(cross.getElement(), "font-weight", "bold");
}
#Override
public void onMouseOut(MouseOutEvent event) {
DOM.setStyleAttribute(cross.getElement(), "font-weight", "normal");
}
}
Label cross = new Label("X"); // The close button
crossHandler crosshandler = new crossHandler();
HTML caption = new HTML(); // The caption aka title
HorizontalPanel captionPanel = new HorizontalPanel(); // Contains caption and cross
/**
* Creates an empty dialog box. It should not be shown until its child widget
* has been added using {#link #add(Widget)}.
*/
public MyDialogBox()
{
this(false);
}
/**
* Creates an empty dialog box specifying its "auto-hide" property. It should
* not be shown until its child widget has been added using
* {#link #add(Widget)}.
*
* #param autoHide <code>true</code> if the dialog should be automatically
* hidden when the user clicks outside of it
*/
public MyDialogBox(boolean autoHide) {
this(autoHide, true);
}
/**
* Creates an empty dialog box specifying its "auto-hide" property. It should
* not be shown until its child widget has been added using
* {#link #add(Widget)}.
*
* #param autoHide <code>true</code> if the dialog should be automatically
* hidden when the user clicks outside of it
* #param modal <code>true</code> if keyboard and mouse events for widgets not
* contained by the dialog should be ignored
*/
public MyDialogBox(boolean autoHide, boolean modal)
{
super(autoHide, modal);
cross.addClickHandler(crosshandler);
cross.addMouseOutHandler(crosshandler);
cross.addMouseOverHandler(crosshandler);
captionPanel.add(caption);
captionPanel.add(cross);
captionPanel.setStyleName("caption");
Element td = getCellElement(0, 1); // Get the cell element that holds the caption
td.setInnerHTML(""); // Remove the old caption
td.appendChild(captionPanel.getElement());
}
#Override
public void setText(String text)
{
caption.setText(text);
}
public String getText()
{
return caption.getText();
}
public void setHtml(String html)
{
caption.setHTML(html);
}
public String getHtml()
{
return caption.getHTML();
}
Note: This code doesn't work. The ClickEvent isn't sent from cross but instead from MyDialogBox regardless of whether you add ClickHandlers to the cross or not, IOW the MyDialogBox is the sender/source and therefor not possible to check against cross. When cross is clicked it doesn't fire the ClickEvent for some reasons.
Edit:
It appears this cannot be done without hacks unless you either write your own DialogBox (almost) from scratch or fix issue 1405. Of course there are number of existing libraries that have already solved this problem, i.e. SmartGWT and GWT-Ext, but their implementation is made mostly from scratch.
So to answer your question in one sentence: Yes there is a way, but you're not gonna like it :)
I guess a simple answer to this is to instantiate a widget to replace the standard Caption widget from DialogBox.
I created a caption that has a button at right and you can pick a reference to it.
Then you can add any click event you desire.
In GWT 2.4 I used the following solution:
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.dom.client.MouseWheelHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.DialogBox.Caption;
/**
* #author Cristiano Sumariva
*/
public class ButtonCaption extends HorizontalPanel implements Caption
{
protected InlineLabel text;
protected PushButton closeDialog;
/**
* #return the button at caption
*/
public PushButton getCloseButton()
{
return closeDialog;
}
public ButtonCaption( String label )
{
super();
setWidth( "100%" );
setStyleName( "Caption" ); // so you have same styling as standard caption widget
closeDialog = new PushButton();
add( text = new InlineLabel( label ) );
add( closeDialog );
setCellWidth( closeDialog, "1px" ); // to make button cell minimal enough to it
}
/* (non-Javadoc)
* #see com.google.gwt.event.dom.client.HasMouseDownHandlers#addMouseDownHandler(com.google.gwt.event.dom.client.MouseDownHandler)
*/
#Override
public HandlerRegistration addMouseDownHandler( MouseDownHandler handler )
{
return addMouseDownHandler( handler );
}
/* (non-Javadoc)
* #see com.google.gwt.event.dom.client.HasMouseUpHandlers#addMouseUpHandler(com.google.gwt.event.dom.client.MouseUpHandler)
*/
#Override
public HandlerRegistration addMouseUpHandler( MouseUpHandler handler )
{
return addMouseUpHandler( handler );
}
/* (non-Javadoc)
* #see com.google.gwt.event.dom.client.HasMouseOutHandlers#addMouseOutHandler(com.google.gwt.event.dom.client.MouseOutHandler)
*/
#Override
public HandlerRegistration addMouseOutHandler( MouseOutHandler handler )
{
return addMouseOutHandler( handler );
}
/* (non-Javadoc)
* #see com.google.gwt.event.dom.client.HasMouseOverHandlers#addMouseOverHandler(com.google.gwt.event.dom.client.MouseOverHandler)
*/
#Override
public HandlerRegistration addMouseOverHandler( MouseOverHandler handler )
{
return addMouseOverHandler( handler );
}
/* (non-Javadoc)
* #see com.google.gwt.event.dom.client.HasMouseMoveHandlers#addMouseMoveHandler(com.google.gwt.event.dom.client.MouseMoveHandler)
*/
#Override
public HandlerRegistration addMouseMoveHandler( MouseMoveHandler handler )
{
return addMouseMoveHandler( handler );
}
/* (non-Javadoc)
* #see com.google.gwt.event.dom.client.HasMouseWheelHandlers#addMouseWheelHandler(com.google.gwt.event.dom.client.MouseWheelHandler)
*/
#Override
public HandlerRegistration addMouseWheelHandler( MouseWheelHandler handler )
{
return addMouseWheelHandler( handler );
}
/* (non-Javadoc)
* #see com.google.gwt.user.client.ui.HasHTML#getHTML()
*/
#Override
public String getHTML()
{
return getElement().getInnerHTML();
}
/* (non-Javadoc)
* #see com.google.gwt.user.client.ui.HasHTML#setHTML(java.lang.String)
*/
#Override
public void setHTML( String html )
{
remove( text );
insert( text, 1 );
}
/* (non-Javadoc)
* #see com.google.gwt.user.client.ui.HasText#getText()
*/
#Override
public String getText()
{
return text.getText();
}
/* (non-Javadoc)
* #see com.google.gwt.user.client.ui.HasText#setText(java.lang.String)
*/
#Override
public void setText( String text )
{
this.text.setText( text );
}
/* (non-Javadoc)
* #see com.google.gwt.safehtml.client.HasSafeHtml#setHTML(com.google.gwt.safehtml.shared.SafeHtml)
*/
#Override
public void setHTML( SafeHtml html )
{
setHTML( html.asString() );
}
}
Extends the DialogBox to use the new ButtonCaption available
class CaptionCloseableDialogBox extends DialogBox
{
public CaptionCloseableDialogBox()
{
super( new ButtonCaption( "dialog box title" ) );
setAutoHideEnabled( false );
ButtonCaption ref = (ButtonCaption) this.getCaption();
PushButton closeButton = ref.getCloseButton();
// apply button face here closeButton;
closeButton.addClickHandler( /* attach any click handler here like close this dialog */ );
}
}
Hope it helps any.
Check out the active project:
http://code.google.com/p/gwt-mosaic/
Their noble goal is, as mentioned on their page:
The goal is to provide a complete widget set by keeping the API as close as possible to the GWT's standard widgets API.
Have been trapped in the GXT vortex. Not at all a fan of how they require users to use entirely different API for listeners, etc. On their part this makes sense. After all, GXT is just a port of their existing javascript libraries. But I've been looking for this MOSAIC project for too long...
Just using GWT and no external libraries you can intercept the click events on the caption element and perform a hit test to see if the x,y mouse coord is within the bounds of the anchor element (or other element your using as a ClickHandler).
// 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();
I realize this is ridiculously old, but you can just use absolute positioning with top and right of 0 to get a widget in the upper right. The dialog box is itself absolutely positioned, so the positioning of your widget will be against it.
This works if you just wan't a simple solution for the question asked:
Image button = new Image("images/cancel.png");
button.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent event) {
hide();
}
});
button.setStyleName("dialog-close");
HorizontalPanel header = new HorizontalPanel();
header.add(new HTML("Example Tool"));
header.add(button);
setHTML(header.getElement().getInnerHTML());
You can find the closeable dialogbox in google code under the project synthfuljava.
It is actually called scrollable dialog box with a close X button at the caption.
The following blog explains the impediments that had to be overcome in order for thecaption X button to be able to listen to the click event to let it work:
http://h2g2java.blessedgeek.com/2009/07/gwt-useable-closeable-scrollable.html
I think the ButtonCaption of cavila is the best solution, but there is a bug in the implementation of the caption. The call of one of the overidden methods causes a infinitive loop because the method calls itself recursively.
To prevent this you you can call the method on the InlineLabel text instead:
#Override
public HandlerRegistration addMouseDownHandler( MouseDownHandler handler ) {
return text.addMouseDownHandler( handler );
}
The GWT dialog box's top level DIV has absolute positioning, so you can do the same with your close button. This allows you to put it in the body of the dialog as far as the DOM is concerned, but make it physically appear in the caption.
In my example below, I place it in the exact upper right of the dialog, and center it on the caption using padding.
<ui:style>
.close {
position: absolute;
top: 0;
right: 0;
padding: 3px 3px 1px 3px !important;
border-radius: 4px;
margin: 5px;
}
</ui:style>
<g:PushButton ui:field="closeButton" addStyleNames="{style.close}">
<g:upFace image='{closeIcon}'/>
<g:downFace image='{closeIcon}'/>
<g:upHoveringFace image='{closeIcon}'/>
<g:downHoveringFace image='{closeIcon}'/>
<g:upDisabledFace image='{closeIcon}'/>
<g:downDisabledFace image='{closeIcon}'/>
</g:PushButton>