The largest Interview Solution Library on the web


« Previous | 1 | 2 | 3 | Next »

GWT - COMPLEX WIDGETS


“Complex widgets” allow users to perform advanced interaction capability with the application. Every complex widget inherits properties from Widget class which in turn inherits properties from UIObject.
S.N.Widget & Description
1GWT UIObject Class
This widget contains text, not interpreted as HTML using a <div>element, causing it to be displayed with block layout.
2GWT Widget Class
This widget can contain HTML text and displays the html content using a <div> element, causing it to be displayed with block layout.
GWT - UIObject Class

Introduction

The class UIObject is the superclass for all user-interface objects. It simply wraps a DOM element, and cannot receive events. It provides direct child classes like Widget, MenuItem, MenuItemSeparator, TreeItem.
  • All UIObject objects can be styled using CSS.
  • Every UIObject has a primary style name that identifies the key CSS style rule that should always be applied to it.
  • More complex styling behavior can be achieved by manipulating an object's secondary style names.
Class Declaration

Following is the declaration for com.google.gwt.user.client.ui.UIObject class:

public abstract class UIObject
extends java.lang.Object

Field

Following are the fields for com.google.gwt.user.client.ui.UIObject class:
  • public static final java.lang.String DEBUG_ID_PREFIX -- The element ID that you specify will be prefixed by the static string DEBUG_ID_PREFIX.
Class Constructors
S.N.Constructor & Description
1UIObject()
This creates a UIObject for the child classes.
Class Methods
S.N.Method & Description
1void addStyleDependentName(java.lang.String styleSuffix) Adds a dependent style name by specifying the style name's suffix.
2void addStyleName(java.lang.String style) Adds a secondary or dependent style name to this object.
3static void ensureDebugId(Element elem, java.lang.String id) Ensure that elem has an ID property set, which allows it to integrate with third-party libraries and test tools.
4protected static void ensureDebugId(Element elem, java.lang.String baseID, java.lang.String id) Set the debug id of a specific element.
5ensureDebugId(java.lang.String id) Ensure that the main Element for this UIObject has an ID property set, which allows it to integrate with third-party libraries and test tools.
6int getAbsoluteLeft() Gets the object's absolute left position in pixels, as measured from the browser window's client area.
7int getAbsoluteTop() Gets the object's absolute top position in pixels, as measured from the browser window's client area.
8Element getElement() Gets a handle to the object's underlying DOM element.
9int getOffsetHeight() Gets the object's offset height in pixels.
10int getOffsetWidth() Gets the object's offset width in pixels.
11protected Element getStyleElement() Template method that returns the element to which style names will be applied.
12java.lang.String getStyleName() Gets all of the object's style names, as a space-separated list.
13protected static java.lang.String getStyleName(Element elem) Gets all of the element's style names, as a space-separated list.
14java.lang.String getStylePrimaryName() Gets the primary style name associated with the object.
15protected static java.lang.String getStylePrimaryName(Element elem) Gets the element's primary style name.
16java.lang.String getTitle() Gets the title associated with this object.
17boolean isVisible() Determines whether or not this object is visible.
18static boolean isVisible(Element elem) Determines whether element is visible or not.
19protected void onEnsureDebugId(java.lang.String baseID) Called when the user sets the id using the ensureDebugId(String) method.
20void removeStyleDependentName(java.lang.String styleSuffix) Removes a dependent style name by specifying the style name's suffix.
21void removeStyleName(java.lang.String style) Removes a style name.
22protected void setElement(Element elem) Sets this object's browser element.
23protected void setElement(Element elem) Sets this object's browser element.
24void setHeight(java.lang.String height) Sets the object's height.
25void setPixelSize(int width, int height) Sets the object's size, in pixels, not including decorations such as border, margin, and padding.
26void setSize(java.lang.String width, java.lang.String height) Sets the object's size.
27protected static void setStyleName(Element elem, java.lang.String styleName) Clears all of the element's style names and sets it to the given style.
28protected static void setStyleName(Element elem, java.lang.String style, boolean add) This convenience method adds or removes a style name for a given element.
29void setStyleName(java.lang.String style) Clears all of the object's style names and sets it to the given style.
30protected static void setStylePrimaryName(Element elem, java.lang.String style) Sets the element's primary style name and updates all dependent style names.
31void setStylePrimaryName(java.lang.String style) Sets the object's primary style name and updates all dependent style names.
32void setTitle(java.lang.String title) Sets the title associated with this object.
33void setVisible(boolean visible) Sets whether this object is visible.
34static void setVisible(Element elem, boolean visible) Sets whether this element is visible
35void setWidth(java.lang.String width) Sets the object's width.
36java.lang.String toString() This method is overridden so that any object can be viewed in the debugger as an HTML snippet.
37void unsinkEvents(int eventBitsToRemove) Removes a set of events from this object's event list.
Methods inherited

This class inherits methods from the following classes:
  • java.lang.Object
GWT - Widget Class

Introduction

The class Widget is the base class for the majority of user-interface objects. Widget adds support for receiving events from the browser and being added directly to panels. Class Declaration

Following is the declaration for com.google.gwt.user.client.ui.Widget class:

public class Widget
extends UIObject
implements EventListener

Field

Following are the fields for com.google.gwt.user.client.ui.Widget class:
  • public static final java.lang.String DEBUG_ID_PREFIX -- The element ID that you specify will be prefixed by the static string DEBUG_ID_PREFIX.
Class Constructors
S.N.Constructor & Description
1Widget()
This creates a Widget for the child classes.
Class Methods
S.N.Method & Description
1protected <H extends EventHandler> HandlerRegistration addDomHandler(H handler, DomEvent.Type<H> type) Adds a native event handler to the widget and sinks the corresponding native event.
2protected <H extends EventHandler> HandlerRegistration addHandler(H handler, GwtEvent.Type<H> type) Adds this handler to the widget.
3protected void delegateEvent(Widget target, GwtEvent<?> event) Fires an event on a child widget.
4protected void doAttachChildren() If a widget implements HasWidgets, it must override this method and call onAttach() for each of its child widgets.
5protected void doDetachChildren() If a widget implements HasWidgets, it must override this method and call onDetach() for each of its child widgets.
6void fireEvent(GwtEvent<?> event) Fires the given event to all the appropriate handlers.
7protected int getHandlerCount(GwtEvent.Type<?> type) Gets the number of handlers listening to the event type.
8Widget getParent() Gets this widget's parent panel.
9boolean isAttached() Determines whether this widget is currently attached to the browser's document (i.e., there is an unbroken chain of widgets between this widget and the underlying browser document).
10protected boolean isOrWasAttached() Has this widget ever been attached?
11protected void onAttach() This method is called when a widget is attached to the browser's document.
12void onBrowserEvent(Event event) Fired whenever a browser event is received.
13protected void onDetach() This method is called when a widget is detached from the browser's document.
14protected void onLoad() Gets a handle to the object's underlying DOM element.
15protected void onUnload() This method is called immediately before a widget will be detached from the browser's document.
16void removeFromParent() Removes this widget from its parent widget.
17void sinkEvents(int eventBitsToAdd) Overridden to defer the call to super.sinkEvents until the first time this widget is attached to the dom, as a performance enhancement.
Methods inherited

This class inherits methods from the following classes:
  • com.google.gwt.user.client.ui.UIObject

Complex Widgets

Following are few important Complex Widgets:
S.N.Widget & Description
1Tree
This widget represents a standard hierarchical tree widget. The tree contains a hierarchy of TreeItems that the user can open, close, and select.
2MenuBar
This widget represents a standard menu bar widget. A menu bar can contain any number of menu items, each of which can either fire a Command or open a cascaded menu bar.
3DatePicker
This widget represents a standard GWT date picker.
4CellTree
This widget represents a view of a tree. This widget will only work in standards mode, which requires that the HTML page in which it is run have an explicit <!DOCTYPE> declaration.
5CellList
This widget represents a single column list of cells.
6CellTable
This widget represents a tabular view that supports paging and columns.
7CellBrowser
This widget represents a browsable view of a tree in which only a single node per level may be open at one time. This widget will only work in standards mode, which requires that the HTML page in which it is run have an explicit <!DOCTYPE> declaration.
GWT - Tree Widget

Introduction

The Tree widget represents a standard hierarchical tree widget. The tree contains a hierarchy of TreeItems that the user can open, close, and select.

Class Declaration

Following is the declaration for com.google.gwt.user.client.ui.Tree class:

public class Tree
extends Widget
implements HasWidgets, SourcesTreeEvents, HasFocus,
HasAnimation, HasAllKeyHandlers, HasAllFocusHandlers,
HasSelectionHandlers, HasOpenHandlers,
HasCloseHandlers, SourcesMouseEvents, HasAllMouseHandlers

CSS Style Rules

Following default CSS Style rules will be applied to all the Tree widget. You can override it as per your requirements.

.gwt-Tree {}
.gwt-TreeItem {}
.gwt-TreeItem-selected {}

Class Constructors
S.N.Constructor & Description
1Tree() Constructs an empty tree.
2Tree(TreeImages images) Constructs a tree that uses the specified image bundle for images.
3Tree(TreeImages images, boolean useLeafImages) Constructs a tree that uses the specified image bundle for images.
Class methods
S.N.Function name & Description
1void add(Widget widget) Adds the widget as a root tree item.
2void addFocusListener(FocusListener listener) Adds a listener interface to receive mouse events.
3TreeItem addItem(java.lang.String itemText) Adds a simple tree item containing the specified text.
4void addItem(TreeItem item) Adds an item to the root level of this tree.
5TreeItem addItem(Widget widget) Adds a new tree item containing the specified widget.
6void addKeyboardListener(KeyboardListener listener) Adds a listener interface to receive keyboard events.
7void addMouseListener(MouseListener listener)
8void addTreeListener(TreeListener listener) Adds a listener interface to receive tree events.
9void clear() Clears all tree items from the current tree.
10protected void doAttachChildren() If a widget implements HasWidgets, it must override this method and call onAttach() for each of its child widgets.
11protected void doDetachChildren() If a widget implements HasWidgets, it must override this method and call onDetach() for each of its child widgets.
12void ensureSelectedItemVisible() Ensures that the currently-selected item is visible, opening its parents and scrolling the tree as necessary.
13java.lang.String getImageBase() Deprecated. Use Tree(TreeImages) as it provides a more efficent and manageable way to supply a set of images to be used within a tree.
14TreeItem getItem(int index) Gets the top-level tree item at the specified index.
15int getItemCount() Gets the number of items contained at the root of this tree.
16TreeItem getSelectedItem() Gets the currently selected item.
17int getTabIndex() Gets the widget's position in the tab index.
18boolean isAnimationEnabled()
19protected boolean isKeyboardNavigationEnabled(TreeItem currentItem) Indicates if keyboard navigation is enabled for the Tree and for a given TreeItem.
20java.util.Iterator<<Widget> iterator() Gets an iterator for the contained widgets.
21void onBrowserEvent(Event event) Fired whenever a browser event is received.
22protected void onEnsureDebugId(java.lang.String baseID) Affected Elements: -root = The root TreeItem.
23protected void onLoad() This method is called immediately after a widget becomes attached to the browser's document.
24boolean remove(Widget w) Removes a child widget.
25void removeFocusListener(FocusListener listener) Removes a previously added listener interface.
26void removeItem(TreeItem item) Removes an item from the root level of this tree.
27void removeItems() Removes all items from the root level of this tree.
28void removeKeyboardListener(KeyboardListener listener) Removes a previously added listener interface.
29void removeTreeListener(TreeListener listener) Removes a previously added listener interface.
30void setAccessKey(char key) Sets the widget's 'access key'.
31void setAnimationEnabled(boolean enable) Enable or disable animations.
32void setFocus(boolean focus) Explicitly focus/unfocus this widget.
33void setImageBase(java.lang.String baseUrl) Deprecated. Use Tree(TreeImages) as it provides a more efficent and manageable way to supply a set of images to be used within a tree.
34void setSelectedItem(TreeItem item) Selects a specified item.
35void setSelectedItem(TreeItem item, boolean fireEvents) Selects a specified item.
36void setTabIndex(int index) Sets the widget's position in the tab index.
37java.util.Iterator<TreeItem> treeItemIterator() Iterator of tree items.
Methods Inherited

This class inherits methods from the following classes:
  • com.google.gwt.user.client.ui.UIObject
  • com.google.gwt.user.client.ui.Widget
  • java.lang.Object
Tree Widget Example

This example will take you through simple steps to show usage of a Tree Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter:
StepDescription
1Create a project with a name HelloWorld under a package com.jtc as explained in the GWT - Create Application chapter.
2Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.javaas explained below. Keep rest of the files unchanged.
3Compile and run the application to verify the result of the implemented logic.
Following is the content of the modified module descriptorsrc/com.jtc/HelloWorld.gwt.xml.

<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='helloworld'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. -->
<inherits name='com.google.gwt.user.theme.clean.Clean'/>
<!-- Specify the app entry point class. -->
<entry-point class='com.jtc.client.HelloWorld'/>
<!-- Specify the paths for translatable code -->
<source path='client'/>
<source path='shared'/>
</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body{
text-align: center;
font-family: verdana, sans-serif;
}
h1{
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
.gwt-Label {
font-weight: bold;
color: maroon;
}
.gwt-Tree .gwt-TreeItem {
padding: 1px 0px;
margin: 0px;
white-space: nowrap;
cursor: hand;
cursor: pointer;
}
.gwt-Tree .gwt-TreeItem-selected {
background: #ebeff9;
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
<head>
<title>Hello World</title>
<link rel="stylesheet" href="HelloWorld.css"/>
<script language="javascript" src="helloworld/helloworld.nocache.js">
</script>
</head>
<body>
<h1>Tree Widget Demonstration</h1>
<div id="gwtContainer"></div>
</body>
</html>

Let us have following content of Java file src/com.jtc/HelloWorld.java which will demonstrate use of Tree widget.

package com.jtc.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.VerticalPanel;
public class HelloWorld implements EntryPoint {
public void onModuleLoad() {
//create a label
final Label labelMessage = new Label();
labelMessage.setWidth("300");
// Create a root tree item as department
TreeItem department = new TreeItem("Department");
//create other tree items as department names
TreeItem salesDepartment = new TreeItem("Sales");
TreeItem marketingDepartment = new TreeItem("Marketing");
TreeItem manufacturingDepartment = new TreeItem("Manufacturing");
//create other tree items as employees
TreeItem employee1 = new TreeItem("Robert");
TreeItem employee2 = new TreeItem("Joe");
TreeItem employee3 = new TreeItem("Chris");
//add employees to sales department
salesDepartment.addItem(employee1);
salesDepartment.addItem(employee2);
salesDepartment.addItem(employee3);
//create other tree items as employees
TreeItem employee4 = new TreeItem("Mona");
TreeItem employee5 = new TreeItem("Tena");
//add employees to marketing department
marketingDepartment.addItem(employee4);
marketingDepartment.addItem(employee5);
//create other tree items as employees
TreeItem employee6 = new TreeItem("Rener");
TreeItem employee7 = new TreeItem("Linda");
//add employees to sales department
manufacturingDepartment.addItem(employee6);
manufacturingDepartment.addItem(employee7);
//add departments to department item
department.addItem(salesDepartment);
department.addItem(marketingDepartment);
department.addItem(manufacturingDepartment);
//create the tree
Tree tree = new Tree();
//add root item to the tree
tree.addItem(department);
tree.addSelectionHandler(new SelectionHandlerL<TreeItem>() {
@Override
public void onSelection(SelectionEvent<TreeItem> event) {
labelMessage.setText("Selected Value: "
+ event.getSelectedItem().getText());
}
});
// Add text boxes to the root panel.
VerticalPanel panel = new VerticalPanel();
panel.setSpacing(10);
panel.add(tree);
panel.add(labelMessage);
//add the tree to the root panel
RootPanel.get("gwtContainer").add(panel);
}
}

Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce the following result:

Selecting any value in tree, will update a message below the tree displaying the selected value.

GWT - MenuBar Widget

Introduction

The MenuBar widget represents a standard menu bar widget. A menu bar can contain any number of menu items, each of which can either fire a Command or open a cascaded menu bar.
Class Declaration

Following is the declaration for com.google.gwt.user.client.ui.MenuBar class:

public class MenuBar
extends Widget
implements PopupListener, HasAnimation,
HasCloseHandlers<PopupPanel>

CSS Style Rules

Following default CSS Style rules will be applied to all the MenuBar widget. You can override it as per your requirements.

.gwt-MenuBar {}
.gwt-MenuBar-horizontal {}
.gwt-MenuBar-vertical{}
.gwt-MenuBar .gwt-MenuItem {}
.gwt-MenuBar .gwt-MenuItem-selected {}
.gwt-MenuBar .gwt-MenuItemSeparator {}
.gwt-MenuBar .gwt-MenuItemSeparator .menuSeparatorInner {}
.gwt-MenuBarPopup .menuPopupTopLeft {}
.gwt-MenuBarPopup .menuPopupTopLeftInner {}
.gwt-MenuBarPopup .menuPopupTopCenter {}
.gwt-MenuBarPopup .menuPopupTopCenterInner {}
.gwt-MenuBarPopup .menuPopupTopRight {}
.gwt-MenuBarPopup .menuPopupTopRightInner {}
.gwt-MenuBarPopup .menuPopupMiddleLeft {}
.gwt-MenuBarPopup .menuPopupMiddleLeftInner {}
.gwt-MenuBarPopup .menuPopupMiddleCenter {}
.gwt-MenuBarPopup .menuPopupMiddleCenterInner {}
.gwt-MenuBarPopup .menuPopupMiddleRight {}
.gwt-MenuBarPopup .menuPopupMiddleRightInner {}
.gwt-MenuBarPopup .menuPopupBottomLeft {}
.gwt-MenuBarPopup .menuPopupBottomLeftInner {}
.gwt-MenuBarPopup .menuPopupBottomCenter {}
.gwt-MenuBarPopup .menuPopupBottomCenterInner {}
.gwt-MenuBarPopup .menuPopupBottomRight {}
.gwt-MenuBarPopup .menuPopupBottomRightInner {}

Class Constructors
S.N.Constructor & Description
1MenuBar() Creates an empty horizontal menu bar.
2MenuBar(boolean vertical) Creates an empty menu bar.
3MenuBar(boolean vertical, MenuBar.MenuBarImages images) Deprecated. replaced by MenuBar(boolean, Resources)
4MenuBar(boolean vertical, MenuBar.Resources resources) Creates an empty menu bar that uses the specified ClientBundle for menu images.
5MenuBar(MenuBar.MenuBarImages images) Deprecated. replaced by MenuBar(Resources)
6MenuBar(MenuBar.Resources resources) Creates an empty horizontal menu bar that uses the specified ClientBundle for menu images.
Class Methods
S.N.Function name & Description
1HandlerRegistration addCloseHandler(CloseHandler handler) Adds a CloseEvent handler.
2MenuItem addItem(MenuItem item) Adds a menu item to the bar.
3MenuItem addItem(SafeHtml html, Command cmd) Adds a menu item to the bar containing SafeHtml, that will fire the given command when it is selected.
4MenuItem addItem(SafeHtml html, MenuBar popup) Adds a menu item to the bar, that will open the specified menu when it is selected.
5MenuItem addItem(java.lang.String text, boolean asHTML, Command cmd) Adds a menu item to the bar, that will fire the given command when it is selected.
6MenuItem addItem(java.lang.String text, boolean asHTML, MenuBar popup) Adds a menu item to the bar, that will open the specified menu when it is selected.
7MenuItem addItem(java.lang.String text, Command cmd) Adds a menu item to the bar, that will fire the given command when it is selected.
8MenuItem addItem(java.lang.String text, MenuBar popup) Adds a menu item to the bar, that will open the specified menu when it is selected.
9MenuItemSeparator addSeparator() Adds a thin line to the MenuBar to separate sections of MenuItems.
10MenuItemSeparator addSeparator(MenuItemSeparator separator) Adds a thin line to the MenuBar to separate sections of MenuItems.
11void clearItems() Removes all menu items from this menu bar.
12void closeAllChildren(boolean focus) Closes this menu and all child menu popups.
13void focus() Give this MenuBar focus.
14boolean getAutoOpen() Gets whether this menu bar's child menus will open when the mouse is moved over it.
15int getItemIndex(MenuItem item) Get the index of a MenuItem.
16protected java.util.List getItems() Returns a list containing the MenuItem objects in the menu bar.
17protected MenuItem getSelectedItem() Returns the MenuItem that is currently selected (highlighted) by the user.
18int getSeparatorIndex(MenuItemSeparator item) Get the index of a MenuItemSeparator.
19MenuItem insertItem(MenuItem item, int beforeIndex) Adds a menu item to the bar at a specific index.
20MenuItemSeparator insertSeparator(int beforeIndex) Adds a thin line to the MenuBar to separate sections of MenuItems at the specified index.
21MenuItemSeparator insertSeparator(MenuItemSeparator separator, int beforeIndex) Adds a thin line to the MenuBar to separate sections of MenuItems at the specified index.
22boolean isAnimationEnabled() Returns true if animations are enabled, false if not.
23boolean isFocusOnHoverEnabled() Check whether or not this widget will steal keyboard focus when the mouse hovers over it.
24void moveSelectionDown() Moves the menu selection down to the next item.
25void moveSelectionUp() Moves the menu selection up to the previous item.
26void onBrowserEvent(Event event) Fired whenever a browser event is received.
27protected void onDetach() This method is called when a widget is detached from the browser's document.
28protected void onEnsureDebugId(java.lang.String baseID) Affected Elements: -item# = the MenuItem at the specified index.
29void onPopupClosed(PopupPanel sender, boolean autoClosed) Deprecated. Use addCloseHandler(CloseHandler) instead
30void removeItem(MenuItem item) Removes the specified menu item from the bar.
31void removeSeparator(MenuItemSeparator separator) Removes the specified MenuItemSeparator from the bar.
32void selectItem(MenuItem item) Select the given MenuItem, which must be a direct child of this MenuBar.
33void setAnimationEnabled(boolean enable) Enable or disable animations.
34void setAutoOpen(boolean autoOpen) Sets whether this menu bar's child menus will open when the mouse is moved over it.
35void setFocusOnHoverEnabled(boolean enabled) Enable or disable auto focus when the mouse hovers over the MenuBar.
Methods Inherited

This class inherits methods from the following classes:
  • com.google.gwt.user.client.ui.UIObject
  • com.google.gwt.user.client.ui.Widget
  • java.lang.Object
Menu Bar Widget Example

This example will take you through simple steps to show usage of a MenuBar Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter:
StepDescription
1Create a project with a name HelloWorld under a package com.jtc as explained in the GWT - Create Application chapter.
2Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.javaas explained below. Keep rest of the files unchanged.
3Compile and run the application to verify the result of the implemented logic.
Following is the content of the modified module descriptorsrc/com.jtc/HelloWorld.gwt.xml.

<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='helloworld'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. -->
<inherits name='com.google.gwt.user.theme.clean.Clean'/>
<!-- Specify the app entry point class. -->
<entry-point class='com.jtc.client.HelloWorld'/>
<!-- Specify the paths for translatable code -->
<source path='client'/>
<source path='shared'/>
</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body{
text-align: center;
font-family: verdana, sans-serif;
}
h1{
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
.gwt-MenuBar {
cursor: default;
}
.gwt-MenuBar .gwt-MenuItem {
cursor: default;
font-family: Arial Unicode MS, Arial, sans-serif;
font-size: 12px;
}
.gwt-MenuBar .gwt-MenuItem-selected {
background: #E3E8F3;
}
.gwt-MenuBar-horizontal {
background: #e3e8f3 url(images/hborder.png) repeat-x 0px -2003px; border: 1px solid #e0e0e0;
}
.gwt-MenuBar-horizontal .gwt-MenuItem {
padding: 5px 10px;
vertical-align: bottom;
color: #000;
font-weight: bold;
}
.gwt-MenuBar-horizontal .gwt-MenuItemSeparator {
width: 1px;
padding: 0px;
margin: 0px;
border: 0px;
border-left: 1px solid #ccc;
background: white;
}
.gwt-MenuBar-horizontal .gwt-MenuItemSeparator .menuSeparatorInner {
width: 1px;
height: 1px;
background:white;
}
.gwt-MenuBar-vertical {
margin-top: 0px;
margin-left: 0px;
background: white;
}
.gwt-MenuBar-vertical table {
border-collapse: collapse;
}
.gwt-MenuBar-vertical .gwt-MenuItem {
padding: 2px 40px 2px 1px;
}
.gwt-MenuBar-vertical .gwt-MenuItemSeparator {
padding: 2px 0px;
}
.gwt-MenuBar-vertical .gwt-MenuItemSeparator .menuSeparatorInner {
height: 1px;
padding: 0px;
border: 0px;
border-top: 1px solid #ccc;
overflow: hidden;
}
.gwt-MenuBar-vertical .subMenuIcon {
padding-right: 4px;
}
.gwt-MenuBar-vertical .subMenuIcon-selected {
background: #E3E8F3;
}
.gwt-MenuBarPopup {
margin: 0px 0px 0px 3px;
}
.gwt-MenuBarPopup .menuPopupTopLeftInner {
width: 5px;
height: 5px;
zoom: 1;
}
.gwt-MenuBarPopup .menuPopupTopRightInner {
width: 8px;
height: 5px;
zoom: 1;
}
.gwt-MenuBarPopup .menuPopupBottomLeftInner {
width: 5px;
height: 8px;
zoom: 1;
}
.gwt-MenuBarPopup .menuPopupBottomRightInner {
width: 8px;
height: 8px;
zoom: 1;
}
.gwt-MenuBarPopup .menuPopupTopLeft {
background: url(images/corner.png) no-repeat 0px -36px;
-background: url(images/corner_ie6.png) no-repeat 0px -36px;
}
.gwt-MenuBarPopup .menuPopupTopRight {
background: url(images/corner.png) no-repeat -5px -36px;
-background: url(images/corner_ie6.png) no-repeat -5px -36px;
}
.gwt-MenuBarPopup .menuPopupBottomLeft {
background: url(images/corner.png) no-repeat 0px -41px;
-background: url(images/corner_ie6.png) no-repeat 0px -41px;
}
.gwt-MenuBarPopup .menuPopupBottomRight {
background: url(images/corner.png) no-repeat -5px -41px;
-background: url(images/corner_ie6.png) no-repeat -5px -41px;
}
html>body .gwt-MenuBarPopup {
}
* html .gwt-MenuBarPopup .menuPopupTopLeftInner {
width: 5px;
height: 5px;
overflow: hidden;
}
* html .gwt-MenuBarPopup .menuPopupTopRightInner {
width: 8px;
height: 5px;
overflow: hidden;
}
* html .gwt-MenuBarPopup .menuPopupBottomLeftInner {
width: 5px;
height: 8px;
overflow: hidden;
}
* html .gwt-MenuBarPopup .menuPopupBottomRightInner {
width: 8px;
height: 8px;
overflow: hidden;
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
<head>
<title>Hello World</title>
<link rel="stylesheet" href="HelloWorld.css"/>
<script language="javascript" src="helloworld/helloworld.nocache.js">
</script>
</head>
<body>
<h1>MenuBar Widget Demonstration</h1>
<div id="gwtContainer"></div>
</body>
</html>

Let us have following content of Java file src/com.jtc/HelloWorld.java which will demonstrate use of MenuBar widget.

package com.jtc.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.RootPanel;
public class HelloWorld implements EntryPoint {
private void showSelectedMenuItem(String menuItemName){
Window.alert("Menu item: "+menuItemName+" selected");
}
public void onModuleLoad() {
// Create a menu bar
MenuBar menu = new MenuBar();
menu.setAutoOpen(true);
menu.setWidth("100px");
menu.setAnimationEnabled(true);
// Create the file menu
MenuBar fileMenu = new MenuBar(true);
fileMenu.setAnimationEnabled(true);
fileMenu.addItem("New", new Command() {
@Override
public void execute() {
showSelectedMenuItem("New");
}
});
fileMenu.addItem("Open", new Command() {
@Override
public void execute() {
showSelectedMenuItem("Open");
}
});
fileMenu.addSeparator();
fileMenu.addItem("Exit", new Command() {
@Override
public void execute() {
showSelectedMenuItem("Exit");
}
});
// Create the edit menu
MenuBar editMenu = new MenuBar(true);
editMenu.setAnimationEnabled(true);
editMenu.addItem("Undo", new Command() {
@Override
public void execute() {
showSelectedMenuItem("Undo");
}
});
editMenu.addItem("Redo", new Command() {
@Override
public void execute() {
showSelectedMenuItem("Redo");
}
});
editMenu.addItem("Cut", new Command() {
@Override
public void execute() {
showSelectedMenuItem("Cut");
}
});
editMenu.addItem("Copy", new Command() {
@Override
public void execute() {
showSelectedMenuItem("Copy");
}
});
editMenu.addItem("Paste", new Command() {
@Override
public void execute() {
showSelectedMenuItem("Paste");
}
});
menu.addItem(new MenuItem("File", fileMenu));
menu.addSeparator();
menu.addItem(new MenuItem("Edit", editMenu));
//add the menu to the root panel
RootPanel.get("gwtContainer").add(menu);
}
}

Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, then this will produce the following result:

Selecting any value in menubar, will popup an alert message showing the selected value.

GWT - Date Picker Widget

Introduction

The DatePicker widget represents a standard GWT date picker.

Class Declaration

Following is the declaration for com.google.gwt.user.datepicker.client.DatePicker class:

public class DatePicker
extends Composite
implements HasHighlightHandlers<java.util.Date>,
HasShowRangeHandlers<java.util.Date>, HasValue<java.util.Date>

CSS Style Rules

Following default CSS Style rules will be applied to all the DatePicker widget. You can override it as per your requirements.

.gwt-DatePicker { }
.datePickerMonthSelector { }
.datePickerMonth { }
.datePickerPreviousButton { }
.datePickerNextButton { }
.datePickerDays { }
.datePickerWeekdayLabel { }
.datePickerWeekendLabel { }
.datePickerDay { }
.datePickerDayIsToday { }
.datePickerDayIsWeekend { }
.datePickerDayIsFiller { }
.datePickerDayIsValue { }
.datePickerDayIsDisabled { }
.datePickerDayIsHighlighted { }
.datePickerDayIsValueAndHighlighted { }

Class Constructors
S.N.Constructor & Description
1DatePicker() Create a new date picker.
2protected DatePicker(MonthSelector monthSelector, CalendarView view, CalendarModel model) Create a new date picker.
Class Methods
S.N.Function name & Description
1HandlerRegistration addHighlightHandler(HighlightHandler<java.util.Date> handler) Adds a HighlightEvent handler.
2Handler Registration add Show Range Handler (ShowRangeHandler<java.util.Date> handler) Adds a ShowRangeEvent handler.
3Handler Registration addShow Range Handler AndFire (Show Range Handler<java.util.Date> handler) Adds a show range handler and immediately activate the handler on the current view.
4void addStyleToDates(java.lang.String styleName, java.util.Date date) Add a style name to the given dates.
5void addStyleToDates(java.lang.String styleName, java.util.Date date, java.util.Date... moreDates) Add a style name to the given dates.
6void add Style To Dates(java.lang.String style Name, java.lang.Iterable<java.util.Date> dates) Add a style name to the given dates.
7void addTransientStyleToDates(java.lang.String styleName, java.util.Date date) Adds the given style name to the specified dates, which must be visible.
8void addTransientStyleToDates(java.lang.String styleName, java.util.Date date, java.util.Date... moreDates) Adds the given style name to the specified dates, which must be visible.
9void add Transient Style ToDates(java.lang.String styleName, java.lang.Iterable<java.util.Date> dates) Adds the given style name to the specified dates, which must be visible.
10Handler Registration addValue Change Handler(ValueChangeHandler<java.util.Date> handler) Adds a ValueChangeEvent handler.
11java.util.Date getCurrentMonth() Gets the current month the date picker is showing.
12java.util.Date getFirstDate() Returns the first shown date.
13java.util.Date getHighlightedDate() Gets the highlighted date (the one the mouse is hovering over), if any.
14java.util.Date getLastDate() Returns the last shown date.
15protected CalendarModel getModel() Gets the CalendarModel associated with this date picker.
16protected MonthSelector getMonthSelector() Gets the MonthSelector associated with this date picker.
17java.lang.String getStyleOfDate(java.util.Date date) Gets the style associated with a date (does not include styles set via addTransientStyleToDates(java.lang.String, java.util.Date)).
18java.util.Date getValue() Returns the selected date, or null if none is selected.
19protected CalendarView getView() Gets the CalendarView associated with this date picker.
20boolean isDateEnabled(java.util.Date date) Is the visible date enabled?
21boolean isDateVisible(java.util.Date date) Is the date currently shown in the date picker?
22void onLoad() This method is called immediately after a widget becomes attached to the browser's document.
23protected void refreshAll() Refreshes all components of this date picker.
24void removeStyleFromDates(java.lang.String styleName, java.util.Date date) Removes the styleName from the given dates (even if it is transient).
25void removeStyleFromDates(java.lang.String styleName, java.util.Date date, java.util.Date... moreDates) Removes the styleName from the given dates (even if it is transient).
26void remove Style From Dates(java.lang.String styleName, java.lang.Iterable<java.util.Date> dates) Removes the styleName from the given dates (even if it is transient).
27void setCurrentMonth(java.util.Date month) Sets the date picker to show the given month, use getFirstDate() and getLastDate() to access the exact date range the date picker chose to display.
28void setStyleName(java.lang.String styleName) Sets the date picker style name.
29void setTransientEnabledOnDates(boolean enabled, java.util.Date date) Sets a visible date to be enabled or disabled.
30void setTransientEnabledOnDates(boolean enabled, java.util.Date date, java.util.Date... moreDates) Sets a visible date to be enabled or disabled.
31void set Transient Enabled On Dates(boolean enabled, java.lang.Iterable<java.util.Date> dates) Sets a group of visible dates to be enabled or disabled.
32protected void setup() Sets up the date picker.
33void setValue(java.util.Date newValue) Sets the DatePicker's value.
34void setValue(java.util.Date newValue, boolean fireEvents) Sets the DatePicker's value.
Methods Inherited

This class inherits methods from the following classes:
  • com.google.gwt.user.client.ui.UIObject
  • com.google.gwt.user.client.ui.Widget
  • com.google.gwt.user.client.ui.Composite
  • java.lang.Object
Datepicker Widget Example

This example will take you through simple steps to show usage of a DatePicker Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter:
StepDescription
1Create a project with a name HelloWorld under a package com.jtc as explained in the GWT - Create Application chapter.
2Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.javaas explained below. Keep rest of the files unchanged.
3Compile and run the application to verify the result of the implemented logic.
Following is the content of the modified module descriptor src/com.jtc/HelloWorld.gwt.xml.

<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='helloworld'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. -->
<inherits name='com.google.gwt.user.theme.clean.Clean'/>
<!-- Specify the app entry point class. -->
<entry-point class='com.jtc.client.HelloWorld'/>
<!-- Specify the paths for translatable code -->
<source path='client'/>
<source path='shared'/>
</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body{
text-align: center;
font-family: verdana, sans-serif;
}
h1{
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}
.gwt-DatePicker {
border: 1px solid #ccc;
border-top:1px solid #999;
cursor: default;
}
.gwt-DatePicker td,
.datePickerMonthSelector td:focus {
outline: none;
}
.datePickerMonthSelector td:focus {
outline: none;
}
.datePickerDays {
width: 100%;
background: white;
}
.datePickerDay,
.datePickerWeekdayLabel,
.datePickerWeekendLabel {
font-size: 85%;
text-align: center;
padding: 4px;
outline: none;
font-weight:bold;
color:#333;
border-right: 1px solid #EDEDED;
border-bottom: 1px solid #EDEDED;
}
.datePickerWeekdayLabel,
.datePickerWeekendLabel {
background: #fff;
padding: 0px 4px 2px;
cursor: default;
color:#666;
font-size:70%;
font-weight:normal;
}
.datePickerDay {
padding: 4px 7px;
cursor: hand;
cursor: pointer;
}
.datePickerDayIsWeekend {
background: #f7f7f7;
}
.datePickerDayIsFiller {
color: #999;
font-weight:normal;
}
.datePickerDayIsValue {
background: #d7dfe8;
}
.datePickerDayIsDisabled {
color: #AAAAAA;
font-style: italic;
}
.datePickerDayIsHighlighted {
background: #F0E68C;
}
.datePickerDayIsValueAndHighlighted {
background: #d7dfe8;
}
.datePickerDayIsToday {
padding: 3px;
color: #00f;
background: url(images/hborder.png) repeat-x 0px -2607px;
}
.datePickerMonthSelector {
width: 100%;
padding: 1px 0 5px 0;
background: #fff;
}
.datePickerPreviousButton,
.datePickerNextButton {
font-size: 120%;
line-height: 1em;
color: #3a6aad;
cursor: hand;
cursor: pointer;
font-weight: bold;
padding: 0px 4px;
outline: none;
}
td.datePickerMonth {
text-align: center;
vertical-align: middle;
white-space: nowrap;
font-size: 100%;
font-weight: bold;
color: #333;
}
.gwt-DateBox {
padding: 5px 4px;
border: 1px solid #ccc;
border-top: 1px solid #999;
font-size: 100%;
}
.gwt-DateBox input {
width: 8em;
}
.dateBoxFormatError {
background: #ffcccc;
}
.dateBoxPopup {
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
<head>
<title>Hello World</title>
<link rel="stylesheet" href="HelloWorld.css"/>
<script language="javascript" src="helloworld/helloworld.nocache.js">
</script>
</head>
<body>
<h1>DatePicker Widget Demonstration</h1>
<div id="gwtContainer"></div>
</body>
</html>

Let us have following content of Java file src/com.jtc/HelloWorld.java which will demonstrate use of Tree widget.

package com.jtc.client;
import java.util.Date;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.user.datepicker.client.DatePicker;
public class HelloWorld implements EntryPoint {
public void onModuleLoad() {
// Create a basic date picker
DatePicker datePicker = new DatePicker();
final Label text = new Label();
// Set the value in the text box when the user selects a date
datePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {
@Override
public void onValueChange(ValueChangeEvent<Date> event) {
Date date = event.getValue();
String dateString =
DateTimeFormat.getFormat("MM/dd/yyyy").format(date);
text.setText(dateString);
}
});
// Set the default value
datePicker.setValue(new Date(), true);
// Create a DateBox
DateTimeFormat dateFormat = DateTimeFormat.getFormat("MM/dd/yyyy");
DateBox dateBox = new DateBox();
dateBox.setFormat(new DateBox.DefaultFormat(dateFormat));
Label selectLabel = new Label("Permanent DatePicker:");
Label selectLabel2 = new Label("DateBox with popup DatePicker:");
// Add widgets to the root panel.
VerticalPanel vPanel = new VerticalPanel();
vPanel.setSpacing(10);
vPanel.add(selectLabel);
vPanel.add(text);
vPanel.add(datePicker);
vPanel.add(selectLabel2);
vPanel.add(dateBox);
RootPanel.get("gwtContainer").add(vPanel);
}
}

Once you are are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, then will produce the following result:

GWT - Cell Tree Widget

Introduction

The CellTree widget represents a view of a tree.

public class CellTree
extends AbstractCellTree
implements HasAnimation, Focusable

Class Constructors
S.N.Constructor & Description
1CellTree(TreeViewModel viewModel, T rootValue) Construct a new CellTree.
2CellTree(TreeViewModel viewModel, T rootValue, CellTree.Resources resources) Construct a new CellTree.
Class Methods
S.N.Function name & Description
1protected char getAccessKey() Get the access key.
2CellTree.NodeAnimation getAnimation() Get the animation used to open and close nodes in this tree if animations are enabled.
3int getDefaultNodeSize() Get the default maximum number of children to display under each tree node.
4TreeNode getRootTreeNode() Get the root TreeNode.
5int getTabIndex() Gets the widget's position in the tab index.
6boolean isAnimationEnabled() Returns true if animations are enabled, false if not.
7protected void onBlur() Called when the keyboard selected node loses focus.
8void onBrowserEvent(Event event) Fired whenever a browser event is received.
9protected void onFocus() Called when the keyboard selected node gains focus.
10void setAccessKey(char key) Sets the widget's 'access key'.
11void setAnimation(CellTree.NodeAnimation animation) Set the animation used to open and close nodes in this tree.
12void setAnimationEnabled(boolean enable) Enable or disable animations.
13void setDefaultNodeSize(int defaultNodeSize) Set the default number of children to display beneath each child node.
14void setFocus(boolean focused) Explicitly focus/unfocus this widget.
15void setTabIndex(int index) Sets the widget's position in the tab index.
Methods Inherited

This class inherits methods from the following classes:
  • com.google.gwt.user.client.ui.UIObject
  • com.google.gwt.user.client.ui.Widget
  • com.google.gwt.user.client.ui.Composite
  • com.google.gwt.user.cellview.client.AbstractCellTree
  • java.lang.Object
Cell Tree Widget Example

This example will take you through simple steps to show usage of a CellTree Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter:
StepDescription
1Create a project with a name HelloWorld under a package com.jtc as explained in the GWT - Create Application chapter.
2Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.javaas explained below. Keep rest of the files unchanged.
3Compile and run the application to verify the result of the implemented logic.
Following is the content of the modified module descriptorsrc/com.jtc/HelloWorld.gwt.xml.

<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='helloworld'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. -->
<inherits name='com.google.gwt.user.theme.clean.Clean'/>
<!-- Specify the app entry point class. -->
<entry-point class='com.jtc.client.HelloWorld'/>
<!-- Specify the paths for translatable code -->
<source path='client'/>
<source path='shared'/>
</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body{
text-align: center;
font-family: verdana, sans-serif;
}
h1{
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
<head>
<title>Hello World</title>
<link rel="stylesheet" href="HelloWorld.css"/>
<script language="javascript" src="helloworld/helloworld.nocache.js">
</script>
</head>
<body>
<h1>CellTree Widget Demonstration</h1>
<div id="gwtContainer"></div>
</body>
</html>

Let us have following content of Java file src/com.jtc/HelloWorld.java which will demonstrate use of CellTree widget.

package com.jtc.client;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.CellTree;
import com.google.gwt.user.cellview.client.
HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.TreeNode;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.view.client.TreeViewModel;
public class HelloWorld implements EntryPoint {
/**
* A list of songs.
*/
private static class Playlist {
private final String name;
private final List<String> songs = new ArrayList7lt;String>();
public Playlist(String name) {
this.name = name;
}
/**
* Add a song to the playlist.
*
* @param name the name of the song
*/
public void addSong(String name) {
songs.add(name);
}
public String getName() {
return name;
}
/**
* Return the list of songs in the playlist.
*/
public List<String> getSongs() {
return songs;
}
}
/**
* A composer of classical music.
*/
private static class Composer {
private final String name;
private final List<Playlist> playlists = new ArrayList<Playlist>();
public Composer(String name) {
this.name = name;
}
/**
* Add a playlist to the composer.
*
* @param playlist the playlist to add
*/
public Playlist addPlaylist(Playlist playlist) {
playlists.add(playlist);
return playlist;
}
public String getName() {
return name;
}
/**
* Return the rockin' playlist for this composer.
*/
public List<Playlist> getPlaylists() {
return playlists;
}
}
/**
* The model that defines the nodes in the tree.
*/
private static class CustomTreeModel implements TreeViewModel {
private final List<Composer> composers;
/**
* This selection model is shared across all leaf nodes.
* A selection model can also be shared across all nodes
* in the tree, or each set of child nodes can have
* its own instance. This gives you flexibility to
* determine how nodes are selected.
*/
private final SingleSelectionModel<String> selectionModel
= new SingleSelectionModel<String>();
public CustomTreeModel() {
// Create a database of information.
composers = new ArrayList<Composer>();
// Add compositions by Beethoven.
{
Composer beethoven = new Composer("Beethoven");
composers.add(beethoven);
Playlist concertos = beethoven.addPlaylist(
new Playlist("Concertos"));
concertos.addSong("No. 1 - C");
concertos.addSong("No. 2 - B-Flat Major");
concertos.addSong("No. 3 - C Minor");
concertos.addSong("No. 4 - G Major");
concertos.addSong("No. 5 - E-Flat Major");
Playlist quartets = beethoven.addPlaylist(
new Playlist("Quartets"));
quartets.addSong("Six String Quartets");
quartets.addSong("Three String Quartets");
quartets.addSong("Grosse Fugue for String Quartets");
Playlist sonatas = beethoven.addPlaylist(
new Playlist("Sonatas"));
sonatas.addSong("Sonata in A Minor");
sonatas.addSong("Sonata in F Major");
Playlist symphonies = beethoven.addPlaylist(
new Playlist("Symphonies"));
symphonies.addSong("No. 2 - D Major");
symphonies.addSong("No. 2 - D Major");
symphonies.addSong("No. 3 - E-Flat Major");
symphonies.addSong("No. 4 - B-Flat Major");
symphonies.addSong("No. 5 - C Minor");
symphonies.addSong("No. 6 - F Major");
symphonies.addSong("No. 7 - A Major");
symphonies.addSong("No. 8 - F Major");
symphonies.addSong("No. 9 - D Minor");
}
// Add compositions by Brahms.
{
Composer brahms = new Composer("Brahms");
composers.add(brahms);
Playlist concertos = brahms.addPlaylist(
new Playlist("Concertos"));
concertos.addSong("Violin Concerto");
concertos.addSong("Double Concerto - A Minor");
concertos.addSong("Piano Concerto No. 1 - D Minor");
concertos.addSong("Piano Concerto No. 2 - B-Flat Major");
Playlist quartets = brahms.addPlaylist(
new Playlist("Quartets"));
quartets.addSong("Piano Quartet No. 1 - G Minor");
quartets.addSong("Piano Quartet No. 2 - A Major");
quartets.addSong("Piano Quartet No. 3 - C Minor");
quartets.addSong("String Quartet No. 3 - B-Flat Minor");
Playlist sonatas = brahms.addPlaylist(
new Playlist("Sonatas"));
sonatas.addSong("Two Sonatas for Clarinet - F Minor");
sonatas.addSong("Two Sonatas for Clarinet - E-Flat Major");
Playlist symphonies = brahms.addPlaylist(
new Playlist("Symphonies"));
symphonies.addSong("No. 1 - C Minor");
symphonies.addSong("No. 2 - D Minor");
symphonies.addSong("No. 3 - F Major");
symphonies.addSong("No. 4 - E Minor");
}
// Add compositions by Mozart.
{
Composer mozart = new Composer("Mozart");
composers.add(mozart);
Playlist concertos = mozart.addPlaylist(
new Playlist("Concertos"));
concertos.addSong("Piano Concerto No. 12");
concertos.addSong("Piano Concerto No. 17");
concertos.addSong("Clarinet Concerto");
concertos.addSong("Violin Concerto No. 5");
concertos.addSong("Violin Concerto No. 4");
}
}
/**
* Get the {@link NodeInfo} that provides the children of the
* specified value.
*/
public <T> NodeInfo<?> getNodeInfo(T value) {
if (value == null) {
// LEVEL 0.
// We passed null as the root value. Return the composers.
// Create a data provider that contains the list of composers.
ListDataProvider<Composer> dataProvider
= new ListDataProvider<HelloWorld.Composer>(
composers);
// Create a cell to display a composer.
Cell<HelloWorld.Composer> cell
= new AbstractCell<HelloWorld.Composer>() {
@Override
public void render(Composer value, Object key,
SafeHtmlBuilder sb) {
if (value != null) {
sb.appendHtmlConstant(" ");
sb.appendEscaped(value.getName());
}
}
};
// Return a node info that pairs the data provider and the cell.
return new DefaultNodeInfo<Composer>(dataProvider, cell);
} else if (value instanceof Composer) {
// LEVEL 1.
// We want the children of the composer. Return the playlists.
ListDataProvider<HelloWorld.Playlist> dataProvider
= new ListDataProvider<HelloWorld.Playlist>(
((Composer) value).getPlaylists());
Cell<HelloWorld.Playlist> cell =
new AbstractCell<HelloWorld.Playlist>() {
@Override
public void render(Playlist value, Object key,
SafeHtmlBuilder sb) {
if (value != null) {
sb.appendHtmlConstant(" ");
sb.appendEscaped(value.getName());
}
}
};
return new DefaultNodeInfo<Playlist>(dataProvider, cell);
} else if (value instanceof Playlist) {
// LEVEL 2 - LEAF.
// We want the children of the playlist. Return the songs.
ListDataProvider<String> dataProvider
= new ListDataProvider<String>(
((Playlist) value).getSongs());
// Use the shared selection model.
return new DefaultNodeInfo<String>(dataProvider, new TextCell(),
selectionModel, null);
}
return null;
}
/**
* Check if the specified value represents a leaf node.
* Leaf nodes cannot be opened.
*/
public boolean isLeaf(Object value) {
// The leaf nodes are the songs, which are Strings.
if (value instanceof String) {
return true;
}
return false;
}
}
public void onModuleLoad() {
// Create a model for the tree.
TreeViewModel model = new CustomTreeModel();
//Get CellTree style using its BasicResources
//CellTree.Resources res = GWT.create(CellTree.BasicResources.class);
/*
* Create the tree using the model. We use <code>null</code>
* as the default value of the root node. The default value will
* be passed to CustomTreeModel#getNodeInfo();
*/
CellTree tree = new CellTree(model, null);
tree.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
// Open the first playlist by default.
TreeNode rootNode = tree.getRootTreeNode();
TreeNode firstPlaylist = rootNode.setChildOpen(0, true);
firstPlaylist.setChildOpen(0, true);
VerticalPanel panel = new VerticalPanel();
panel.setBorderWidth(1);
panel.setWidth("300");
panel.add(tree);
// Add the widgets to the root panel.
RootPanel.get().add(panel);
}
}

Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, then this will produce the following result:

GWT - Cell List Widget

Introduction

The CellList widget represents a single column list of cells.

Class Declaration

Following is the declaration for com.google.gwt.user.cellview.client.CellList<T> class:

public class CellList<T>
extends AbstractHasData<T>

Class Constructors
S.N.Constructor & Description
1CellList(Cell<T> cell) Construct a new CellList.
2CellList(Cell<T> cell, CellList.Resources resources) Construct a new CellList with the specified CellList.Resources.
3CellList(Cell<T> cell, CellList.Resources resources, ProvidesKey<T> keyProvider) Construct a new CellList with the specified CellList.Resources and key provider.
4CellList(Cell<T> cell, ProvidesKey<T> keyProvider) Construct a new CellList with the specified key provider.
Class Methods
S.N.Function name & Description
1protected boolean dependsOnSelection() Check whether or not the cells in the view depend on the selection state.
2protected void doSelection(Event event, T value, int indexOnPage) Deprecated. use Abstract HasData.add Cell Preview Handler(com.google.gwt.view.client.Cell Preview Event.Handler) instead.
3protected void fireEventToCell(Cell.Context context, Event event, Element parent, T value) Fire an event to the cell.
4protected Cell<T> getCell() Return the cell used to render each item.
5protected Element getCellParent(Element item) Get the parent element that wraps the cell from the list item.
6protected Element getChildContainer() Return the element that holds the rendered cells.
7SafeHtml getEmptyListMessage() Get the message that is displayed when there is no data.
8protected Element getKeyboardSelectedElement() Get the element that has keyboard selection.
9Element getRowElement(int indexOnPage) Get the Element for the specified index.
10protected boolean isKeyboardNavigationSuppressed() Check if keyboard navigation is being suppressed, such as when the user is editing a cell.
11protected void onBlur() Called when the widget is blurred.
12protected void onBrowserEvent2(Event event) Called after AbstractHasData.onBrowserEvent(Event) completes.
13protected void onFocus() Called when the widget is focused.
14protected void renderRowValues(SafeHtmlBuilder sb, java.util.List<T> values, int start, SelectionModel<? super T> selectionModel) Render all row values into the specified SafeHtmlBuilder.
15protected boolean resetFocusOnCell() Reset focus on the currently focused cell.
16void setEmptyListMessage(SafeHtml html) Set the message to display when there is no data.
17protected void setKeyboardSelected(int index, boolean selected, boolean stealFocus) Update an element to reflect its keyboard selected state.
18protected void setSelected(Element elem, boolean selected) Deprecated. this method is never called by AbstractHasData, render the selected styles in renderRowValues(SafeHtmlBuilder, List, int, SelectionModel)
19void setValueUpdater(ValueUpdater<T> valueUpdater) Set the value updater to use when cells modify items.
Methods Inherited

This class inherits methods from the following classes:
  • com.google.gwt.user.client.ui.UIObject
  • com.google.gwt.user.client.ui.Widget
  • com.google.gwt.user.cellview.client.AbstractHasData
  • java.lang.Object
Celllist Widget Example

This example will take you through simple steps to show usage of a CellList Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter:
StepDescription
1Create a project with a name HelloWorld under a package com.jtc as explained in the GWT - Create Application chapter.
2Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.javaas explained below. Keep rest of the files unchanged.
3Compile and run the application to verify the result of the implemented logic.
Following is the content of the modified module descriptorsrc/com.jtc/HelloWorld.gwt.xml.

<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='helloworld'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. -->
<inherits name='com.google.gwt.user.theme.clean.Clean'/>
<!-- Specify the app entry point class. -->
<entry-point class='com.jtc.client.HelloWorld'/>
<!-- Specify the paths for translatable code -->
<source path='client'/>
<source path='shared'/>
</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body{
text-align: center;
font-family: verdana, sans-serif
}
h1{
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
<head>
<title>Hello World</title>
<link rel="stylesheet" href="HelloWorld.css"/>
<script language="javascript" src="helloworld/helloworld.nocache.js">
</script>
</head>
<body>
<h1>CellList Widget Demonstration</h1>
<div id="gwtContainer"></div>
</body>
</html>

Let us have following content of Java file src/com.jtc/HelloWorld.java which will demonstrate use of CellList widget.

package com.jtc.client;
import java.util.Arrays;
import java.util.List;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.SelectionModel;
import com.google.gwt.view.client.SingleSelectionModel;
public class HelloWorld implements EntryPoint {
/**
* A simple data type that represents a contact.
*/
private static class Contact {
private static int nextId = 0;
private final int id;
private String name;
public Contact(String name) {
nextId++;
this.id = nextId;
this.name = name;
}
}
/**
* A custom {@link Cell} used to render a {@link Contact}.
*/
private static class ContactCell extends AbstractCell<Contact> {
@Override
public void render(Contact value, Object key, SafeHtmlBuilder sb) {
if (value != null) {
sb.appendEscaped(value.name);
}
}
}
/**
* The list of data to display.
*/
private static final List<Contact> CONTACTS = Arrays.asList(new Contact(
"John"), new Contact("Joe"), new Contact("Michael"),
new Contact("Sarah"), new Contact("George"));
public void onModuleLoad() {
/*
* Define a key provider for a Contact. We use the unique ID
* as the key, which allows to maintain selection even if the
* name changes.
*/
ProvidesKey<Contact> keyProvider = new ProvidesKey<Contact>() {
public Object getKey(Contact item) {
// Always do a null check.
return (item == null) ? null : item.id;
}
};
// Create a CellList using the keyProvider.
CellList<Contact> cellList = new CellList<Contact>(new ContactCell(),
keyProvider);
// Push data into the CellList.
cellList.setRowCount(CONTACTS.size(), true);
cellList.setRowData(0, CONTACTS);
// Add a selection model using the same keyProvider.
SelectionModel<Contact> selectionModel
= new SingleSelectionModel<Contact>(
keyProvider);
cellList.setSelectionModel(selectionModel);
/*
* Select a contact. The selectionModel will select based on the
* ID because we used a keyProvider.
*/
Contact sarah = CONTACTS.get(3);
selectionModel.setSelected(sarah, true);
// Modify the name of the contact.
sarah.name = "Sara";
/*
* Redraw the CellList. Sarah/Sara will still be selected because we
* identify her by ID. If we did not use a keyProvider,
* Sara would not be selected.
*/
cellList.redraw();
VerticalPanel panel = new VerticalPanel();
panel.setBorderWidth(1);
panel.setWidth("200");
panel.add(cellList);
// Add the widgets to the root panel.
RootPanel.get().add(panel);
}
}

Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, then this will produce the following result:

GWT - Cell Table Widget

Introduction

The CellTable widget represents a A tabular view that supports paging and columns.

Class Declaration

Following is the declaration for com.google.gwt.user.cellview.client.CellTable<T> class:

public class CellTable<T>
extends AbstractHasData<T>

Class Constructors
S.N.Constructor & Description
1CellTable() Constructs a table with a default page size of 15.
2CellTable(int pageSize) Constructs a table with the given page size.
3CellTable(int pageSize, CellTable.Resources resources) Constructs a table with the given page size with the specified CellTable.BasicResources.
4CellTable(int pageSize, CellTable.Resources resources, ProvidesKey keyProvider) Constructs a table with the given page size, the specified CellTable.BasicResources, and the given key provider.
5CellTable(int pageSize, ProvidesKey<T> keyProvider) Constructs a table with the given page size and the given key provider.
6CellTable(ProvidesKey<T> keyProvider) Constructs a table with a default page size of 15, and the given key provider.
Class Methods
S.N.Function name & Description
1void addColumn(Column<T,?> col) Adds a column to the table.
2void addColumn(Column<T,?> col, Header<?> header) Adds a column to the table with an associated header.
3void addColumn(Column<T,?> col, Header<?> header, Header<?> footer) Adds a column to the table with an associated header and footer.
4void addColumn(Column<T,?> col, SafeHtml headerHtml) Adds a column to the table with an associated SafeHtml header.
5void addColumn(Column<T,?> col, SafeHtml headerHtml, SafeHtml footerHtml) Adds a column to the table with an associated SafeHtml header and footer.
6void addColumn(Column<T,?> col, java.lang.String headerString) Adds a column to the table with an associated String header.
7void add Column (Column<T,?> col, java. lang. String header String, java.lang.String footer String) Adds a column to the table with an associated String header and footer.
8void addColumnStyleName(int index, java.lang.String styleName) Add a style name to the TableColElement at the specified index, creating it if necessary.
9protected Element convertToElements(SafeHtml html) Convert the specified HTML into DOM elements and return the parent of the DOM elements.
10protected boolean dependsOnSelection() Check whether or not the cells in the view depend on the selection state.
11protected void do Selection (Event event, T value, int row, int column) Deprecated. use Abstract Has Data.add Cell Preview Handler(com.google.gwt.view.client. Cell Preview Event.Handler) instead.
12int getBodyHeight() Return the height of the table body.
13protected Element getChildContainer() Return the element that holds the rendered cells.
14int getHeaderHeight() Return the height of the table header.
15protected Element getKeyboardSelectedElement() Get the element that has keyboard selection.
16TableRowElement getRowElement(int row) Get the TableRowElement for the specified row.
17protected boolean isKeyboardNavigationSuppressed() Check if keyboard navigation is being suppressed, such as when the user is editing a cell.
18protected void onBlur() Called when the widget is blurred.
19protected void onBrowserEvent2(Event event) Called after AbstractHasData.onBrowserEvent(Event) completes.
20protected void onFocus() Called when the widget is focused.
21void redrawFooters() Redraw the table's footers.
22void redrawHeaders() Redraw the table's headers.
23void removeColumn(Column col) Remove a column.
24void removeColumn(int index) Remove a column.
25void removeColumnStyleName(int index, java.lang.String styleName) Remove a style from the TableColElement at the specified index.
26protected void renderRowValues(SafeHtmlBuilder sb, java.util.List<T> values, int start, SelectionModel<? super T> selectionModel) Render all row values into the specified SafeHtmlBuilder.
27protected void replaceAllChildren(java.util.List<T> values, SafeHtml html) Replace all children with the specified html.
28protected boolean resetFocusOnCell() Reset focus on the currently focused cell.
29protected void setKeyboardSelected(int index, boolean selected, boolean stealFocus) Update an element to reflect its keyboard selected state.
30void setRowStyles(RowStyles<T> rowStyles) Sets the object used to determine how a row is styled; the change will take effect the next time that the table is rendered.
31protected void setSelected(Element elem, boolean selected) Deprecated. this method is never called by AbstractHasData, render the selected styles in renderRowValues(SafeHtmlBuilder, List, int, SelectionModel)
Methods Inherited

This class inherits methods from the following classes:
  • com.google.gwt.user.client.ui.UIObject
  • com.google.gwt.user.client.ui.Widget
  • com.google.gwt.user.cellview.client.AbstractHasData
  • java.lang.Object
Celltable Widget Example

This example will take you through simple steps to show usage of a CellTable Widget in GWT. The following steps will help you update the GWT application which we created in GWT - Create Application chapter:
StepDescription
1Create a project with a name HelloWorld under a package com.jtc as explained in the GWT - Create Application chapter.
2Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.javaas explained below. Keep rest of the files unchanged.
3Compile and run the application to verify the result of the implemented logic.
Following is the content of the modified module descriptor src/com.jtc/HelloWorld.gwt.xml.

<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='helloworld'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. -->
<inherits name='com.google.gwt.user.theme.clean.Clean'/>
<!-- Specify the app entry point class. -->
<entry-point class='com.jtc.client.HelloWorld'/>
<!-- Specify the paths for translatable code -->
<source path='client'/>
<source path='shared'/>
</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body{
text-align: center;
font-family: verdana, sans-serif;
}
h1{
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
<head>
<title>Hello World</title>
<link rel="stylesheet" href="HelloWorld.css"/>
<script language="javascript" src="helloworld/helloworld.nocache.js">
</script>
</head>
<body>
<h1>CellTable Widget Demonstration</h1>
<div id="gwtContainer"></div>
</body>
</html>

Let us have following content of Java file src/com.jtc/HelloWorld.java which will demonstrate use of CellTable widget.

package com.jtc.client;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import com.google.gwt.cell.client.DateCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client
.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel; public class HelloWorld implements EntryPoint {
/**
* A simple data type that represents a contact.
*/
private static class Contact {
private final String address;
private final Date birthday;
private final String name;
public Contact(String name, Date birthday, String address) {
this.birthday = birthday;
}
}
/**
* The list of data to display.
*/
private static final List<Contact> CONTACTS = Arrays.asList(
new Contact("John", new Date(80, 4, 12), "123 Fourth Avenue"),
new Contact("Joe", new Date(85, 2, 22), "22 Lance Ln"),
new Contact("George",new Date(46, 6, 6),"1600 Pennsylvania Avenue"));
public void onModuleLoad() {
// Create a CellTable.
CellTable<Contact> table = new CellTable<Contact>();
table.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
// Add a text column to show the name.
TextColumn<Contact> nameColumn =
new TextColumn<Contact>() {
@Override
public String getValue(Contact object) {
return object.name;
}
};
table.addColumn(nameColumn, "Name");
// Add a date column to show the birthday.
DateCell dateCell = new DateCell();
Column<Contact, Date> dateColumn
= new Column<Contact, Date>(dateCell) {
@Override
public Date getValue(Contact object) {
return object.birthday;
}
};
table.addColumn(dateColumn, "Birthday");
// Add a text column to show the address.
TextColumn<Contact> addressColumn
= new TextColumn<Contact>() {
@Override
public String getValue(Contact object) {
return object.address;
}
}; table.addColumn(addressColumn, "Address");
// Add a selection model to handle user selection.
final SingleSelectionModel<Contact> selectionModel
= new SingleSelectionModel<Contact>();
table.setSelectionModel(selectionModel);
selectionModel.addSelectionChangeHandler(
new SelectionChangeEvent.Handler() {
public void onSelectionChange(SelectionChangeEvent event) {
Contact selected = selectionModel.getSelectedObject();
if (selected != null) {
Window.alert("You selected: " + selected.name);
}
}
});
// Set the total row count. This isn't strictly necessary,
// but it affects paging calculations, so its good habit to
// keep the row count up to date.
table.setRowCount(CONTACTS.size(), true);
// Push the data into the widget.
table.setRowData(0, CONTACTS);
VerticalPanel panel = new VerticalPanel();
panel.setBorderWidth(1);
panel.setWidth("400");
panel.add(table);
// Add the widgets to the root panel.
RootPanel.get().add(panel);
}
}

Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, then this will produce the following result:

GWT - CellBrowser Widget

Introduction

The CellBrowser widget represents a browsable view of a tree in which only a single node per level may be open at one time.

Class Declaration

Following is the declaration for com.google.gwt.user.cellview.client.CellBrowser<T> class:

public class CellBrowser
extends AbstractCellTree
implements ProvidesResize, RequiresResize, HasAnimation

Class Constructors
S.N.Constructor & Description
1CellBrowser(TreeViewModel viewModel, T rootValue) Construct a new CellBrowser.
2CellBrowser(TreeViewModel viewModel, T rootValue, CellBrowser.Resources resources) Construct a new CellBrowser with the specified CellBrowser.Resources.
Class Methods
S.N.Function name & Description
1protected Widget createPager(HasData display) Create a pager to control the list view.
2int getDefaultColumnWidth() Get the default width of new columns.
3int getMinimumColumnWidth() Get the minimum width of columns.
4TreeNode getRootTreeNode() Get the root TreeNode.
5boolean isAnimationEnabled() Returns true if animations are enabled, false if not.
6void onBrowserEvent(Event event) Fired whenever a browser event is received.
7void onResize() This method must be called whenever the implementor's size has been modified.
8void setAnimationEnabled(boolean enable) Enable or disable animations.
9void setDefaultColumnWidth(int width) Set the default width of new columns.
10void set Keyboard Selection Policy (Has Keyboard Selection Policy.Keyboard Selection Policy policy) Set the HasKeyboardSelectionPolicy.KeyboardSelectionPolicy.
11void setMinimumColumnWidth(int minWidth) Set the minimum width of columns.
Methods Inherited

This class inherits methods from the following classes:
  • com.google.gwt.user.client.ui.UIObject
  • com.google.gwt.user.client.ui.Widget
  • com.google.gwt.user.client.ui.Composite
  • com.google.gwt.user.cellview.client.AbstractCellTree
  • java.lang.Object
Cellbrowser Widget Example

This example will take you through simple steps to show usage of a CellBrowser Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter:
StepDescription
1Create a project with a name HelloWorld under a package com.jtc as explained in the GWT - Create Application chapter.
2Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.javaas explained below. Keep rest of the files unchanged.
3Compile and run the application to verify the result of the implemented logic.
Following is the content of the modified module descriptor src/com.jtc/HelloWorld.gwt.xml.

<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='helloworld'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. -->
<inherits name='com.google.gwt.user.theme.clean.Clean'/>
<!-- Specify the app entry point class. -->
<entry-point class='com.jtc.client.HelloWorld'/>
<!-- Specify the paths for translatable code -->
<source path='client'/>
<source path='shared'/>
</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body{
text-align: center;
font-family: verdana, sans-serif;
}
h1{
font-size: 2em;
font-weight: bold;
color: #777777;
margin: 40px 0px 70px;
text-align: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
<head>
<title>Hello World</title>
<link rel="stylesheet" href="HelloWorld.css"/>
<script language="javascript" src="helloworld/helloworld.nocache.js">
</script>
</head>
<body>
<h1>CellBrowser Widget Demonstration</h1>
<div id="gwtContainer"></div>
</body>
</html>

Let us have following content of Java file src/com.jtc/HelloWorld.java which will demonstrate use of CellBrowser widget.

package com.jtc.client;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.CellBrowser;
import com.google.gwt.user.cellview.client.
HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.view.client.TreeViewModel;
public class HelloWorld implements EntryPoint {
/**
* A list of songs.
*/
private static class Playlist {
private final String name;
private final List<String> songs = new ArrayList<String>();
public Playlist(String name) {
this.name = name;
}
/**
* Add a song to the playlist.
*
* @param name the name of the song
*/
public void addSong(String name) {
songs.add(name);
}
public String getName() {
return name;
}
/**
* Return the list of songs in the playlist.
*/
public List<String> getSongs() {
return songs;
}
}
/**
* A composer of classical music.
*/
private static class Composer {
private final String name;
private final List<Playlist> playlists = new ArrayList<Playlist>();
public Composer(String name) {
this.name = name;
}
/**
* Add a playlist to the composer.
*
* @param playlist the playlist to add
*/
public Playlist addPlaylist(Playlist playlist) {
playlists.add(playlist);
return playlist;
}
public String getName() {
return name;
}
/**
* Return the rockin' playlist for this composer.
*/
public List<Playlist> getPlaylists() {
return playlists;
}
}
/**
* The model that defines the nodes in the tree.
*/
private static class CustomTreeModel implements TreeViewModel {
private final List<Composer> composers;
/**
* This selection model is shared across all leaf nodes.
* A selection model can also be shared across all nodes
* in the tree, or each set of child nodes can have its
* own instance. This gives you flexibility to determine
* how nodes are selected.
*/
private final SingleSelectionModel<String> selectionModel
= new SingleSelectionModel<String>();
public CustomTreeModel() {
// Create a database of information.
composers = new ArrayList<Composer>();
// Add compositions by Beethoven.
{
Composer beethoven = new Composer("Beethoven");
composers.add(beethoven);
Playlist concertos = beethoven.addPlaylist(
new Playlist("Concertos"));
concertos.addSong("No. 1 - C");
concertos.addSong("No. 2 - B-Flat Major");
concertos.addSong("No. 3 - C Minor");
concertos.addSong("No. 4 - G Major");
concertos.addSong("No. 5 - E-Flat Major");
Playlist quartets = beethoven.addPlaylist(
new Playlist("Quartets"));
quartets.addSong("Six String Quartets");
quartets.addSong("Three String Quartets");
quartets.addSong("Grosse Fugue for String Quartets");
Playlist sonatas = beethoven.addPlaylist(
new Playlist("Sonatas"));
sonatas.addSong("Sonata in A Minor");
sonatas.addSong("Sonata in F Major");
Playlist symphonies = beethoven.addPlaylist(
new Playlist("Symphonies"));
symphonies.addSong("No. 2 - D Major");
symphonies.addSong("No. 2 - D Major");
symphonies.addSong("No. 3 - E-Flat Major");
symphonies.addSong("No. 4 - B-Flat Major");
symphonies.addSong("No. 5 - C Minor");
symphonies.addSong("No. 6 - F Major");
symphonies.addSong("No. 7 - A Major");
symphonies.addSong("No. 8 - F Major");
symphonies.addSong("No. 9 - D Minor");
}
// Add compositions by Brahms.
{
Composer brahms = new Composer("Brahms");
composers.add(brahms);
Playlist concertos = brahms.addPlaylist(
new Playlist("Concertos"));
concertos.addSong("Violin Concerto");
concertos.addSong("Double Concerto - A Minor");
concertos.addSong("Piano Concerto No. 1 - D Minor");
concertos.addSong("Piano Concerto No. 2 - B-Flat Major");
Playlist quartets = brahms.addPlaylist(
new Playlist("Quartets"));
quartets.addSong("Piano Quartet No. 1 - G Minor");
quartets.addSong("Piano Quartet No. 2 - A Major");
quartets.addSong("Piano Quartet No. 3 - C Minor");
quartets.addSong("String Quartet No. 3 - B-Flat Minor");
Playlist sonatas = brahms.addPlaylist(
new Playlist("Sonatas"));
sonatas.addSong("Two Sonatas for Clarinet - F Minor");
sonatas.addSong("Two Sonatas for Clarinet - E-Flat Major");
Playlist symphonies = brahms.addPlaylist(
new Playlist("Symphonies"));
symphonies.addSong("No. 1 - C Minor");
symphonies.addSong("No. 2 - D Minor");
symphonies.addSong("No. 3 - F Major");
symphonies.addSong("No. 4 - E Minor");
}
// Add compositions by Mozart.
{
Composer mozart = new Composer("Mozart");
composers.add(mozart);
Playlist concertos = mozart.addPlaylist(
new Playlist("Concertos"));
concertos.addSong("Piano Concerto No. 12");
concertos.addSong("Piano Concerto No. 17");
concertos.addSong("Clarinet Concerto");
concertos.addSong("Violin Concerto No. 5");
concertos.addSong("Violin Concerto No. 4");
}
}
/**
* Get the {@link NodeInfo} that provides the children of the specified
* value.
*/
public <T> NodeInfo<?> getNodeInfo(T value) {
if (value == null) {
// LEVEL 0.
// We passed null as the root value. Return the composers.
// Create a data provider that contains the list of composers.
ListDataProvider<Composer> dataProvider
= new ListDataProvider<Composer>(composers);
//Create a cell to display a composer.
Cell<Composer> cell = new AbstractCell<Composer>(){
@Override
public void render(Composer value, Object key,
SafeHtmlBuilder sb) {
sb.appendEscaped(value.getName());
}
};
// Return a node info that pairs the data provider and the cell.
return new DefaultNodeInfo<Composer>(dataProvider, cell);
} else if (value instanceof Composer) {
// LEVEL 1.
// We want the children of the composer. Return the playlists.
ListDataProvider<Playlist> dataProvider
= new ListDataProvider<Playlist>(
((Composer) value).getPlaylists());
Cell<Playlist> cell = new AbstractCell<Playlist>() {
@Override
public void render(Playlist value, Object key,
SafeHtmlBuilder sb) {
if (value != null) {
sb.appendEscaped(value.getName());
}
}
};
return new DefaultNodeInfo<Playlist>(dataProvider, cell);
} else if (value instanceof Playlist) {
// LEVEL 2 - LEAF.
// We want the children of the playlist. Return the songs.
ListDataProvider<String> dataProvider
= new ListDataProvider<String>(
((Playlist) value).getSongs());
// Use the shared selection model.
return new DefaultNodeInfo<String>(dataProvider, new TextCell(),
selectionModel, null);
}
return null;
}
/**
* Check if the specified value represents a leaf node.
* Leaf nodes cannot be opened.
*/
public boolean isLeaf(Object value) {
// The leaf nodes are the songs, which are Strings.
if (value instanceof String) {
return true;
}
return false;
}
}
public void onModuleLoad() {
// Create a model for the browser.
TreeViewModel model = new CustomTreeModel();
/*
* Create the browser using the model. We use <code>null</code> as the
* default value of the root node. The default value will be passed to
* CustomTreeModel#getNodeInfo();
*/
CellBrowser browser = new CellBrowser(model, null);
browser.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
browser.setHeight("200");
browser.setWidth("630");
VerticalPanel panel = new VerticalPanel();
panel.setBorderWidth(1);
panel.add(browser);
// Add the widgets to the root panel.
RootPanel.get().add(panel);
}
}

Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, then this will produce the following result:
« Previous | 1 | 2 | 3 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com