### Person POJO example for GWT Editor framework quickstart
Source: https://www.gwtproject.org/doc/latest/DevGuideUiEditors.html
Shows a simple POJO used with the GWT Editor framework. No special types are required; methods are needed for property access.
```java
// Regular POJO, no special types needed
public class Person {
Address getAddress();
Person getManager();
String getName();
void setManager(Person manager);
void setName(String name);
}
```
--------------------------------
### loadStockWatcher() setup and loadStocks() call
Source: https://www.gwtproject.org/doc/latest/tutorial/appengine.html
Sets up the stock table's styling and then calls loadStocks() to populate the watch list. The ellipses indicate omitted code that is not part of this example.
```java
private void loadStockWatcher() {
...
stocksFlexTable.setCellPadding(5);
stocksFlexTable.addStyleName("watchList");
stocksFlexTable.getRowFormatter().addStyleName(0, "watchListHeader");
stocksFlexTable.getCellFormatter().addStyleName(0, 1, "watchListNumericColumn");
stocksFlexTable.getCellFormatter().addStyleName(0, 2, "watchListNumericColumn");
stocksFlexTable.getCellFormatter().addStyleName(0, 3, "watchListRemoveColumn");
loadStocks();
...
}
```
--------------------------------
### Quickstart: AutoBean interface declarations, factory, and usage example
Source: https://www.gwtproject.org/doc/latest/DevGuideAutoBeans.html
Shows a complete AutoBean example: declaring bean-like interfaces (Person, Address), a MyFactory interface extending AutoBeanFactory, instantiating beans via GWT.create or AutoBeanFactorySource.create, and serializing/deserializing to JSON. Notes that in non-GWT code, use AutoBeanFactorySource.create(MyFactory.class).
```Java
// Declare any bean-like interface with matching getters and setters, no base type is necessary
interface Person {
Address getAddress();
String getName();
void setName(String name);
void setAddress(Address a);
}
interface Address {
// Other properties, as above
}
// Declare the factory type
interface MyFactory extends AutoBeanFactory {
AutoBean
address();
AutoBean person();
}
class DoSomething() {
// Instantiate the factory
MyFactory factory = GWT.create(MyFactory.class);
// In non-GWT code, use AutoBeanFactorySource.create(MyFactory.class);
Person makePerson() {
// Construct the AutoBean
AutoBean person = factory.person();
// Return the Person interface shim
return person.as();
}
String serializeToJson(Person person) {
// Retrieve the AutoBean controller
AutoBean bean = AutoBeanUtils.getAutoBean(person);
return AutoBeanCodex.encode(bean).getPayload();
}
Person deserializeFromJson(String json) {
AutoBean bean = AutoBeanCodex.decode(factory, Person.class, json);
return bean.as();
}
}
```
--------------------------------
### Start BrowserManagerServer
Source: https://www.gwtproject.org/doc/latest/DevGuideTestingRemoteTesting.html
Start the BrowserManagerServer on a remote system to enable RemoteWeb testing, ensuring the GWT JARs are on the classpath.
```bash
java -cp gwt-user.jar;gwt-dev.jar com.google.gwt.junit.remote.BrowserManagerServer ie8 "C:\Program Files\Internet Explorer\IEXPLORE.EXE"
```
--------------------------------
### JSON product data example
Source: https://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSON.html
Example of JSON encoding product data with nested objects and arrays.
```json
{
"product": {
"name": "Widget",
"company": "ACME, Inc",
"partNumber": "7402-129",
"prices": [
{ "minQty": 1, "price": 12.49 },
{ "minQty": 10, "price": 9.99 },
{ "minQty": 50, "price": 7.99 }
]
}
}
```
--------------------------------
### Example event for selecting permutation
Source: https://www.gwtproject.org/doc/latest/DevGuideLightweightMetrics.html
Example of a Lightweight Metrics event for selecting a permutation during GWT startup. Uses the moduleName 'Showcase', subSystem 'startup', evtGroup 'bootstrap', and type 'selectingPermutation'. Note the millis field uses new Date().getTime() and the line ends with a semicolon.
```json
{
moduleName : 'Showcase',
subSystem : 'startup',
evtGroup : 'bootstrap',
millis : new Date().getTime();
type : 'selectingPermutation'
}
```
--------------------------------
### GWT RuntimeException: Installation problem detected, please reinstall GWT
Source: https://www.gwtproject.org/doc/latest/FAQ_Troubleshooting.html
This is the exception stack trace shown when launching the GWT compiler or development mode fails because the runtime binary installation cannot be located. The error indicates that the installation path is not correctly determined, often because the shared libraries are missing from the classpath. Ensure the path to gwt-dev-.jar still contains the required shared libraries.
```text
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: Installation problem detected, please reinstall GWT
at com.google.gwt.util.tools.Utility.computeInstallationPath(Utility.java:322)
at com.google.gwt.util.tools.Utility.getInstallPath(Utility.java:223)
at com.google.gwt.util.tools.ToolBase.(ToolBase.java:55)
Caused by: java.io.IOException: Cannot determine installation directory; apparently not running from a jar
at com.google.gwt.util.tools.Utility.computeInstallationPath(Utility.java:307)
...
```
--------------------------------
### HelloActivity extends AbstractActivity with start(), mayStop(), and goTo()
Source: https://www.gwtproject.org/doc/latest/DevGuideMvpActivitiesAndPlaces.html
A minimal Activity implementation that extends AbstractActivity and implements HelloView.Presenter. It receives a HelloPlace and ClientFactory in its constructor, uses the ClientFactory to obtain the view and PlaceController, and overrides start(), mayStop(), and goTo(). The mayStop() method returns a non-null warning string to prompt the user before stopping; returning null would suppress the warning.
```java
public class HelloActivity extends AbstractActivity implements HelloView.Presenter {
// Used to obtain views, eventBus, placeController
// Alternatively, could be injected via GIN
private ClientFactory clientFactory;
// Name that will be appended to "Hello,"
private String name;
public HelloActivity(HelloPlace place, ClientFactory clientFactory) {
this.name = place.getHelloName();
this.clientFactory = clientFactory;
}
/**
* Invoked by the ActivityManager to start a new Activity
*/
@Override
public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
HelloView helloView = clientFactory.getHelloView();
helloView.setName(name);
helloView.setPresenter(this);
containerWidget.setWidget(helloView.asWidget());
}
/**
* Ask user before stopping this activity
*/
@Override
public String mayStop() {
return "Please hold on. This activity is stopping.";
}
/**
* Navigate to a new Place in the browser
*/
public void goTo(Place place) {
clientFactory.getPlaceController().goTo(place);
}
}
```
--------------------------------
### Start Xvfb virtual display
Source: https://www.gwtproject.org/doc/latest/FAQ_Troubleshooting.html
Starts Xvfb on display :2 without access control if it is not already running. This command is used to provide a virtual display for GWT compiles and tests in headless environments.
```bash
ps -ef | grep Xvfb | grep -v grep >> /dev/null || Xvfb :2 -ac &
```
--------------------------------
### Launch quoteServer.py from command line
Source: https://www.gwtproject.org/doc/latest/tutorial/Xsite.html
Launch the quoteServer.py script from the command shell. The server starts without immediate output but logs each HTTP request.
```shell
python quoteServer.py
```
--------------------------------
### Run GWT Compiler with Ant
Source: https://www.gwtproject.org/doc/latest/DevGuideCompilingAndDebugging.html
Example output from running the Ant build script for a GWT project, showing successful compilation and linking of permutations.
```text
C:\gwt-2.6.1\samples\Hello>ant
Buildfile: build.xml
libs:
javac:
gwtc:
[java] Compiling module com.google.gwt.sample.hello.Hello
[java] Compiling 5 permutations
[java] Permutation compile succeeded
[java] Linking into war
[java] Link succeeded
[java] Compilation succeeded -- 20.313s
build:
BUILD SUCCESSFUL
Total time: 22 seconds
```
--------------------------------
### Basic CSS Minification Example
Source: https://www.gwtproject.org/doc/latest/DevGuideClientBundle.html
Demonstrates how the compiler removes comments, whitespace, and empty rules.
```css
.div {
/* This is the default background color */
background: blue;
}
.empty {}
```
```css
.div{background:blue;}
```
--------------------------------
### Run application in SuperDevMode
Source: https://www.gwtproject.org/doc/latest/polymer-tutorial/create.html
After generating the project, navigate into the TodoListApp directory, build the WAR, and start SuperDevMode with Maven. This verifies the project was created correctly.
```bash
$ cd TodoListApp
$ mvn war:exploded
$ mvn gwt:devmode
```
--------------------------------
### Resolve module logical name from file path
Source: https://www.gwtproject.org/doc/latest/DevGuideOrganizingProjects.html
Example showing the mapping between a file system path and the logical module name used in GWT.
```text
~/src/com/example/cal/Calendar.gwt.xml
```
```text
com.example.cal.Calendar
```
--------------------------------
### Initialize Loggers in LogExample.java
Source: https://www.gwtproject.org/doc/latest/DevGuideLogging.html
Demonstrates the creation of a child logger, a parent logger, and the root logger using the Logger.getLogger method.
```java
private static Logger childLogger = Logger.getLogger("ParentLogger.Child");
private static Logger parentLogger = Logger.getLogger("ParentLogger");
private static Logger rootLogger = Logger.getLogger("");
```
--------------------------------
### GWT Hello World with Button and ClickHandler
Source: https://www.gwtproject.org/doc/latest/DevGuideCodingBasicsClient.html
Hello World GWT example that creates a Button widget, attaches a ClickHandler that pops up an alert, and adds the button to the RootPanel. Demonstrates basic widget creation, event handling, and DOM modification in the entry point method.
```java
package com.google.gwt.sample.hello.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* Hello World application.
*/
public class Hello implements EntryPoint {
public void onModuleLoad() {
Button b = new Button("Click me", new ClickHandler() {
public void onClick(ClickEvent event) {
Window.alert("Hello, AJAX");
}
});
RootPanel.get().add(b);
}
}
```
--------------------------------
### Final TodoList.java entry point with Polymer.importHref
Source: https://www.gwtproject.org/doc/latest/polymer-tutorial/elements-buildui.html
Final `TodoList.java` entry point. It imports the required Polymer elements and uses `Polymer.importHref` to load them asynchronously, then calls `startApplication()` to add the `Main` widget to the root panel.
```java
package org.gwtproject.tutorial.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
import com.vaadin.polymer.Polymer;
import com.vaadin.polymer.elemental.Function;
import com.vaadin.polymer.iron.element.IronIconElement;
import com.vaadin.polymer.paper.element.*;
import java.util.Arrays;
public class TodoList implements EntryPoint {
public void onModuleLoad() {
Polymer.importHref(Arrays.asList(
"iron-icons/iron-icons.html",
PaperIconItemElement.SRC,
PaperRippleElement.SRC,
IronIconElement.SRC,
PaperDrawerPanelElement.SRC,
PaperHeaderPanelElement.SRC,
PaperToolbarElement.SRC,
PaperFabElement.SRC
), new Function() {
public Object call(Object arg) {
startApplication();
return null;
}
});
}
private void startApplication() {
RootPanel.get().add(new Main());
}
}
```
--------------------------------
### Capture keyboard events with GWT Event.addNativePreviewHandler
Source: https://www.gwtproject.org/doc/latest/DevGuideUiDom.html
Use this GWT code to intercept keyboard events before they are dispatched to the browser. It registers DOM elements as triggers, checks for interesting keycodes, and consumes the event after handling it. The example shows the required setup with Event.addNativePreviewHandler and the NativePreviewHandler inner class.
```java
private ArrayList keyboardEventReceivers = new ArrayList();
/**
* Widgets can register their DOM element object if they would like to be a
* trigger to intercept keyboard events
*/
public void registerForKeyboardEvents(Element e) {
this.keyboardEventReceivers.add(e);
}
/**
* Returns true if this is one of the keys we are interested in
*/
public boolean isInterestingKeycode(int keycode) {
// ...
return false;
}
/**
* Setup the event preview class when the module is loaded.
*/
private void setupKeyboardShortcuts() {
// Define an inner class to handle the event
Event.addNativePreviewHandler(new NativePreviewHandler() {
public void onPreviewNativeEvent(NativePreviewEvent preview) {
NativeEvent event = preview.getNativeEvent();
Element elt = event.getEventTarget().cast();
int keycode = event.getKeyCode();
boolean ctrl = event.getCtrlKey();
boolean shift = event.getShiftKey();
boolean alt = event.getAltKey();
boolean meta = event.getMetaKey();
if (event.getType().equalsIgnoreCase("keypress") || ctrl || shift
|| alt || meta || keyboardEventReceivers.contains(elt)
|| !isInterestingKeycode(keycode)) {
// Tell the event handler to continue processing this event.
return;
}
GWT.log("Processing Keycode" + keycode, null);
handleKeycode(keycode);
// Tell the event handler that this event has been consumed
preview.consume();
}
});
}
/**
* Perform the keycode specific processing
*/
private void handleKeycode(int keycode) {
switch (keycode) {
// ...
}
}
```
--------------------------------
### Final Main.ui.xml with drawer panel and floating action button
Source: https://www.gwtproject.org/doc/latest/polymer-tutorial/elements-buildui.html
Final `Main.ui.xml` file for the tutorial. It defines the complete UI structure with a drawer panel, toolbar, menu items, and the floating action button. The style block uses `is="custom-style"` and includes the `.add` class that sets the `--paper-fab-background` custom property.
```html
Clear All
Clear Done
Settings
About
```
--------------------------------
### Handle RangeChangeEvent to push data into a CellList
Source: https://www.gwtproject.org/doc/latest/DevGuideUiCellWidgets.html
Use this handler to push new data into a CellList when the user pages through the list. The handler receives the new range, creates data for that range (here synchronous, but you could send an asynchronous RPC request), and calls updateRowData(start, data). The example also forces an initial range change with setVisibleRangeAndClearData(new Range(0, 25), true) and sets up a SimplePager to control the list.
```java
/**
* Example of using a {@link RangeChangeEvent.Handler} to push data into a
* {@link CellList} when the range changes.
*/
public class RangeChangeHandlerExample implements EntryPoint {
@Override
public void onModuleLoad() {
// Create a CellList.
CellList cellList = new CellList(new TextCell());
// Add a range change handler.
cellList.addRangeChangeHandler(new RangeChangeEvent.Handler() {
@Override
public void onRangeChange(RangeChangeEvent event) {
Range range = event.getNewRange();
int start = range.getStart();
int length = range.getLength();
// Create the data to push into the view. At this point, you could send
// an asynchronous RPC request to a server.
List data = new ArrayList();
for (int i = start; i < start + length; i++) {
data.add("Item " + i);
}
// Push the data into the list.
updateRowData(start, data);
}
});
// Force the cellList to fire an initial range change event.
cellList.setVisibleRangeAndClearData(new Range(0, 25), true);
// Create paging controls.
SimplePager pager = new SimplePager();
pager.setDisplay(cellList);
// Add the widgets to the root panel.
VerticalPanel vPanel = new VerticalPanel();
vPanel.add(pager);
vPanel.add(cellList);
RootPanel.get().add(vPanel);
}
}
```
--------------------------------
### Unsplit Hello sample with EntryPoint
Source: https://www.gwtproject.org/doc/latest/DevGuideCodeSplitting.html
Initial version of the Hello sample that comes with GWT. It shows a button that displays an alert when clicked, without any code splitting.
```java
public class Hello implements EntryPoint {
public void onModuleLoad() {
Button b = new Button("Click me", new ClickHandler() {
public void onClick(ClickEvent event) {
Window.alert("Hello, AJAX");
}
});
RootPanel.get().add(b);
}
}
```
--------------------------------
### GWT Plural Forms Example
Source: https://www.gwtproject.org/doc/latest/DevGuideI18nMessages.html
Example of plural forms in English where the message changes based on the count.
```text
You have one tree.
You have 2 trees.
```
--------------------------------
### HTML Host Page for GWT Module Loading
Source: https://www.gwtproject.org/doc/latest/DevGuideOrganizingProjects.html
An example HTML page demonstrating the placement of GWT selection scripts and external resources to illustrate the bootstrap sequence.
```html
```
--------------------------------
### Import icon collection with Polymer.importHref
Source: https://www.gwtproject.org/doc/latest/polymer-tutorial/widgets-buildui.html
Loads the Iron icon set using Polymer.importHref before starting the application. The callback starts the app only after the import succeeds.
```java
package org.gwtproject.tutorial;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
import com.vaadin.polymer.Polymer;
import com.vaadin.polymer.elemental.Function;
public class TodoList implements EntryPoint {
public void onModuleLoad() {
// We have to load icon sets before run application
Polymer.importHref("iron-icons/iron-icons.html", new Function() {
public Object call(Object arg) {
// The app is executed when all imports succeed.
startApplication();
return null;
}
});
}
private void startApplication() {
RootPanel.get().add(new Main());
}
}
```
--------------------------------
### Compile-time error example: Messages interface
Source: https://www.gwtproject.org/doc/latest/DevGuideI18nMessages.html
Java interface for a message that takes two arguments, used in the example that produces a compile-time error due to mismatched parameter count.
```java
public interface ErrorMessages extends Messages {
String permissionDenied(int errorCode, String username);
}
```
--------------------------------
### Implement 9-box Layout with ClientBundle and CSS
Source: https://www.gwtproject.org/doc/latest/DevGuideClientBundle.html
A complete example of a 9-box layout using a ClientBundle interface, CSS with value() functions for dynamic sizing, and the corresponding HTML structure.
```java
public interface Resources extends ClientBundle {
Resources INSTANCE = GWT.create(Resources.class);
@Source("bt.png")
@ImageOptions(repeatStyle = RepeatStyle.Horizontal)
ImageResource bottomBorder();
@Source("btl.png")
ImageResource bottomLeftBorder();
@Source("btr.png")
ImageResource bottomRightBorder();
@Source("StyleInjectorDemo.css")
CssResource css();
@Source("lr.png")
@ImageOptions(repeatStyle = RepeatStyle.Vertical)
ImageResource leftBorder();
@Source("rl.png")
@ImageOptions(repeatStyle = RepeatStyle.Vertical)
ImageResource rightBorder();
@Source("tb.png")
@ImageOptions(repeatStyle = RepeatStyle.Horizontal)
ImageResource topBorder();
@Source("tbl.png")
ImageResource topLeftBorder();
@Source("tbr.png")
ImageResource topRightBorder();
}
```
```css
.contentArea {
padding: value('topBorder.getHeight', 'px') value('rightBorder.getWidth', 'px')
value('bottomBorder.getHeight', 'px') value('leftBorder.getWidth', 'px');
}
@sprite .contentAreaTopLeftBorder {
gwt-image: 'topLeftBorder';
position: absolute;
top:0;
left: 0;
}
@sprite .contentAreaTopBorder {
gwt-image: 'topBorder';
position: absolute;
top: 0;
left: value('topLeftBorder.getWidth', 'px');
right: value('topRightBorder.getWidth', 'px');
}
@sprite .contentAreaTopRightBorder {
gwt-image: 'topRightBorder';
position: absolute;
top:0;
right: 0;
}
@sprite .contentAreaBottomLeftBorder {
gwt-image: 'bottomLeftBorder';
position: absolute;
bottom: 0;
left: 0;
}
@sprite .contentAreaBottomBorder {
gwt-image: 'bottomBorder';
position: absolute;
bottom: 0;
left: value('bottomLeftBorder.getWidth', 'px');
right: value('bottomRightBorder.getWidth', 'px');
}
@sprite .contentAreaBottomRightBorder {
gwt-image: 'bottomRightBorder';
position: absolute;
bottom: 0;
right: 0;
}
@sprite .contentAreaLeftBorder {
gwt-image: 'leftBorder';
position: absolute;
top: 0;
left: 0;
height: 100%;
}
@sprite .contentAreaRightBorder {
gwt-image: 'rightBorder';
position: absolute;
top: 0;
right: 0;
height: 100%;
}
```
```html
```
--------------------------------
### Create stock table and lay out widgets in StockWatcher onModuleLoad
Source: https://www.gwtproject.org/doc/latest/tutorial/buildui.html
Two sequential versions of the StockWatcher EntryPoint class. The first creates the stock table header row using FlexTable.setText with row 0 and columns 0-3 for Symbol, Price, Change, and Remove. The second assembles the Add Stock panel (HorizontalPanel with TextBox and Button) and the Main panel (VerticalPanel with the table, add panel, and timestamp label), leaving TODO comments for associating with the host page and moving focus.
```java
package com.google.gwt.sample.stockwatcher.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
public class StockWatcher implements EntryPoint {
private VerticalPanel mainPanel = new VerticalPanel();
private FlexTable stocksFlexTable = new FlexTable();
private HorizontalPanel addPanel = new HorizontalPanel();
private TextBox newSymbolTextBox = new TextBox();
private Button addStockButton = new Button("Add");
private Label lastUpdatedLabel = new Label();
/**
* Entry point method.
*/
public void onModuleLoad() {
// Create table for stock data.
stocksFlexTable.setText(0, 0, "Symbol");
stocksFlexTable.setText(0, 1, "Price");
stocksFlexTable.setText(0, 2, "Change");
stocksFlexTable.setText(0, 3, "Remove");
// TODO Assemble Add Stock panel.
// TODO Assemble Main panel.
// TODO Associate the Main panel with the HTML host page.
// TODO Move cursor focus to the input box.
}
}
```
```java
package com.google.gwt.sample.stockwatcher.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
public class StockWatcher implements EntryPoint {
private VerticalPanel mainPanel = new VerticalPanel();
private FlexTable stocksFlexTable = new FlexTable();
private HorizontalPanel addPanel = new HorizontalPanel();
private TextBox newSymbolTextBox = new TextBox();
private Button addStockButton = new Button("Add");
private Label lastUpdatedLabel = new Label();
/**
* Entry point method.
*/
public void onModuleLoad() {
// Create table for stock data.
stocksFlexTable.setText(0, 0, "Symbol");
stocksFlexTable.setText(0, 1, "Price");
stocksFlexTable.setText(0, 2, "Change");
stocksFlexTable.setText(0, 3, "Remove");
// Assemble Add Stock panel.
addPanel.add(newSymbolTextBox);
addPanel.add(addStockButton);
// Assemble Main panel.
mainPanel.add(stocksFlexTable);
mainPanel.add(addPanel);
mainPanel.add(lastUpdatedLabel);
// TODO Associate the Main panel with the HTML host page.
// TODO Move cursor focus to the input box.
}
}
```
--------------------------------
### Java classes for JSNI constructor examples
Source: https://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html
Java classes used to illustrate JSNI constructor invocation. The example shows a top-level class with two constructors, a static inner class, and an instance inner class.
```java
package pkg;
class TopLevel {
public TopLevel() { ... }
public TopLevel(int i) { ... }
static class StaticInner {
public StaticInner() { ... }
}
class InstanceInner {
public InstanceInner(int i) { ... }
}
}
```
--------------------------------
### Create a CellBrowser with CellBrowser constructor
Source: https://www.gwtproject.org/doc/latest/DevGuideUiCellWidgets.html
Use this constructor to create a CellBrowser instead of a CellTree. The only code difference is the constructor and the CellBrowser.Resources for CSS style and images. The example shows the same data in three levels as the CellTree example, but displayed side-by-side.
```java
// Create the browser using the model.
CellBrowser browser = new CellBrowser(model, "Item 1");
```
--------------------------------
### Wire MVP together in onModuleLoad()
Source: https://www.gwtproject.org/doc/latest/DevGuideMvpActivitiesAndPlaces.html
EntryPoint that wires together the ClientFactory, ActivityManager, and PlaceHistoryHandler in onModuleLoad(). It sets up the main widget and handles the current history to navigate to the URL place or the default place.
```java
public class HelloMVP implements EntryPoint {
private Place defaultPlace = new HelloPlace("World!");
private SimplePanel appWidget = new SimplePanel();
public void onModuleLoad() {
ClientFactory clientFactory = GWT.create(ClientFactory.class);
EventBus eventBus = clientFactory.getEventBus();
PlaceController placeController = clientFactory.getPlaceController();
// Start ActivityManager for the main widget with our ActivityMapper
ActivityMapper activityMapper = new AppActivityMapper(clientFactory);
ActivityManager activityManager = new ActivityManager(activityMapper, eventBus);
activityManager.setDisplay(appWidget);
// Start PlaceHistoryHandler with our PlaceHistoryMapper
AppPlaceHistoryMapper historyMapper= GWT.create(AppPlaceHistoryMapper.class);
PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(historyMapper);
historyHandler.register(placeController, eventBus, defaultPlace);
RootPanel.get().add(appWidget);
// Goes to the place represented on URL else default place
historyHandler.handleCurrentHistory();
}
}
```
--------------------------------
### Inspect GWT Output Directory
Source: https://www.gwtproject.org/doc/latest/DevGuideCompilingAndDebugging.html
Example file listing of the 'war' directory after a successful GWT compilation, showing generated cache files and the nocache entry point.
```text
C:\gwt-2.6.1\samples\Hello>\bin\find war
war
war\hello
war\hello\18EEC2DA45CB5F0C2050E2539AE61FCE.cache.html
war\hello\813B962DC4C22396EA14405DDEF020EE.cache.html
war\hello\86DA1DCEF4F40731BE71E7978CD4776A.cache.html
war\hello\A37FC20FF4D8F11605B2C4C53AF20B6F.cache.html
war\hello\E3C1ABB32E39A126A9194DB727F7742A.cache.html
war\hello\14A43CD7E24B0A0136C2B8B20D6DF3C0.cache.png
war\hello\548CDF11D6FE9011F3447CA200D7FB7F.cache.png
war\hello\9DA92932034707C17CFF15F95086D53F.cache.png
war\hello\A7CD51F9E5A7DED5F85AD1D82BA67A8A.cache.png
war\hello\B8517E9C2E38AA39AB7C0051564224D3.cache.png
war\hello\clear.cache.gif
war\hello\hello.nocache.js
war\hello\hosted.html
war\Hello.html
```
--------------------------------
### JSNI field access example
Source: https://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html
Example of accessing static and instance fields from JSNI. The native method bar demonstrates calling instance and static methods, reading and writing instance fields, and reading a static field. Note the JSNI syntax for method calls and field access.
```java
public class JSNIExample {
String myInstanceField;
static int myStaticField;
void instanceFoo(String s) {
// use s
}
static void staticFoo(String s) {
// use s
}
public native void bar(JSNIExample x, String s) /*-{
// Call instance method instanceFoo() on this
this.@com.google.gwt.examples.JSNIExample::instanceFoo(Ljava/lang/String;)(s);
// Call instance method instanceFoo() on x
x.@com.google.gwt.examples.JSNIExample::instanceFoo(Ljava/lang/String;)(s);
// Call static method staticFoo()
@com.google.gwt.examples.JSNIExample::staticFoo(Ljava/lang/String;)(s);
// Read instance field on this
var val = this.@com.google.gwt.examples.JSNIExample::myInstanceField;
// Write instance field on x
x.@com.google.gwt.examples.JSNIExample::myInstanceField = val + " and stuff";
// Read static field (no qualifier)
@com.google.gwt.examples.JSNIExample::myStaticField = val + " and stuff";
}-*/;
}
```
--------------------------------
### Create a Maven project with webAppCreator
Source: https://www.gwtproject.org/doc/latest/RefCommandLineTools.html
Command to generate a GWT project using the Maven build system.
```bash
webAppCreator -out foo -templates maven,sample,readme com.example.foo.Foo
```
--------------------------------
### GWT HTML widget constructor and setHTML examples
Source: https://www.gwtproject.org/doc/latest/DevGuideSecuritySafeHtml.html
Two examples of using the HTML widget in GWT. The first passes a compile-time constant string to the HTML constructor, which is safe from XSS. The second passes a variable to setHTML, which may be unsafe if the value is attacker-controlled; prefer setText or Label instead.
```java
HTML widget = new HTML("Some text in the widget");
```
```java
widget.setHTML(someText);
```
--------------------------------
### Create an Ant project with webAppCreator
Source: https://www.gwtproject.org/doc/latest/RefCommandLineTools.html
Command to generate a GWT project using the Ant build system.
```bash
webAppCreator -junit /path/to/junit-3.8.1.jar -out foo com.example.foo.Foo
```
--------------------------------
### CSS Selector Merging Example
Source: https://www.gwtproject.org/doc/latest/DevGuideClientBundle.html
Shows how rules with identical selectors are combined.
```css
.div {prop: value;}
.div {foo: bar;}
```
```css
.div {prop:value;foo:bar;}
```
--------------------------------
### English Pluralization Example
Source: https://www.gwtproject.org/doc/latest/DevGuideI18nPluralForms.html
Demonstrates the basic concept of plural forms in English.
```text
You have 1 tree.
You have 2 trees.
```
--------------------------------
### Deployment directory structure for DynaTable sample
Source: https://www.gwtproject.org/doc/latest/DevGuideDeploying.html
Shows the required file layout on the servlet container for the DynaTable sample, including the HTML, CSS, and JavaScript files under webapps/dynatable/.
```text
webapps/dynatable/DynaTable.html
webapps/dynatable/DynaTable.css
webapps/dynatable/dynatable/dynatable.nocache.js
// The rest of your GWT application files under webapps/dynatable/dynatable/
```
--------------------------------
### Add border to stock list with watchList CSS class
Source: https://www.gwtproject.org/doc/latest/tutorial/style.html
Defines the watchListHeader and watchList CSS classes in StockWatcher.css, then applies them to the flex table in StockWatcher.java. The header row gets a blue background and italic white text; the table gets a silver border. Save and refresh in development mode to see the border.
```css
/* stock list header row */
.watchListHeader {
background-color: #2062B8;
color: white;
font-style: italic;
}
/* stock list flex table */
.watchList {
border: 1px solid silver;
padding: 2px;
margin-bottom:6px;
}
```
```java
// Add styles to elements in the stock list table.
stocksFlexTable.getRowFormatter().addStyleName(0, "watchListHeader");
stocksFlexTable.addStyleName("watchList");
```
--------------------------------
### Final Main.java code
Source: https://www.gwtproject.org/doc/latest/polymer-tutorial/elements-applogic.html
The complete Main.java file after adding all application logic. It includes the UiBinder setup, event listeners for adding items and clearing them, and helper methods addItem and closeMenu.
```java
package org.gwtproject.tutorial.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.vaadin.polymer.elemental.*;
import com.vaadin.polymer.paper.element.*;
import java.util.ArrayList;
import java.util.List;
public class Main extends Composite {
interface MainUiBinder extends UiBinder {
}
private static MainUiBinder ourUiBinder = GWT.create(MainUiBinder.class);
@UiField PaperDrawerPanelElement drawerPanel;
@UiField PaperIconItemElement menuClearAll;
@UiField PaperIconItemElement menuClearDone;
@UiField HTMLElement content;
@UiField PaperFabElement addButton;
@UiField PaperDialogElement addItemDialog;
@UiField PaperInputElement titleInput;
@UiField PaperTextareaElement descriptionInput;
@UiField PaperButtonElement confirmAddButton;
private List- items = new ArrayList<>();
public Main() {
initWidget(ourUiBinder.createAndBindUi(this));
addButton.addEventListener("click", new EventListener() {
public void handleEvent(Event event) {
addItemDialog.open();
}
});
confirmAddButton.addEventListener("click", new EventListener() {
public void handleEvent(Event event) {
if (!titleInput.getValue().isEmpty()) {
addItem(titleInput.getValue(), descriptionInput.getValue());
// clear text fields
titleInput.setValue("");
descriptionInput.setValue("");
}
}
});
menuClearAll.addEventListener("click", new EventListener() {
public void handleEvent(Event event) {
closeMenu();
// remove all child elements
while (content.hasChildNodes()) {
content.removeChild(content.getFirstChild());
}
}
});
menuClearDone.addEventListener("click", new EventListener() {
public void handleEvent(Event event) {
closeMenu();
for (Item item : items) {
if (item.isDone()) {
content.removeChild(item.getElement());
items.remove(item);
}
}
}
});
}
private void addItem(String title, String description) {
Item item = new Item();
item.setTitle(title);
item.setDescription(description);
content.appendChild(item.getElement());
items.add(item);
}
private void closeMenu() {
if (drawerPanel.getNarrow()) {
drawerPanel.closeDrawer();
}
}
}
```
--------------------------------
### CSS Property Merging Example
Source: https://www.gwtproject.org/doc/latest/DevGuideClientBundle.html
Rules with identical properties can be merged into a single selector list.
```css
.a {background: blue;}
.b {background: blue;}
```
```css
.a,.b{background:blue;}
```
--------------------------------
### Example JSON data structure
Source: https://www.gwtproject.org/doc/latest/tutorial/JSON.html
A sample JSON array representing stock data returned from a server.
```json
[
{
"symbol": "ABC",
"price": 47.65563005127077,
"change": -0.4426563818062567
},
]
```
--------------------------------
### Split Hello sample using GWT.runAsync
Source: https://www.gwtproject.org/doc/latest/DevGuideCodeSplitting.html
Modified version that splits the Window.alert call into a separate download using GWT.runAsync. The callback implements RunAsyncCallback with onFailure and onSuccess methods.
```java
public class Hello implements EntryPoint {
public void onModuleLoad() {
Button b = new Button("Click me", new ClickHandler() {
public void onClick(ClickEvent event) {
GWT.runAsync(new RunAsyncCallback() {
public void onFailure(Throwable caught) {
Window.alert("Code download failed");
}
public void onSuccess() {
Window.alert("Hello, AJAX");
}
});
}
});
RootPanel.get().add(b);
}
}
```
--------------------------------
### Example JSON output
Source: https://www.gwtproject.org/doc/latest/tutorial/JSONphp.html
This is the expected JSON response format when navigating to the stockPrices.php URL with query parameters.
```json
[{"symbol":"ABC","price":40.485578668179,"change":-0.53944918844604},
{"symbol":"DEF","price":1.3606576154209,"change":0.0051755221198266}]
```
--------------------------------
### Invalid: constant as condition
Source: https://www.gwtproject.org/doc/latest/DevGuideGssVsCss.html
Shows an invalid GSS example: a constant cannot be used as a condition. This code will not compile.
```css
@def MY_BOOLEAN eval("com.module.Foo.staticBooleanFunction()");
@if (MY_BOOLEAN) {
...
}
```
--------------------------------
### Create Main.java and Main.ui.xml for the main screen
Source: https://www.gwtproject.org/doc/latest/polymer-tutorial/elements-buildui.html
Create the main screen of the TodoList application as a UiBinder composite. The Java file defines the Main class that binds the UiBinder template, and the XML file provides the initial empty HTMLPanel container.
```java
package org.gwtproject.tutorial.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
public class Main extends Composite {
interface MainUiBinder extends UiBinder {
}
private static MainUiBinder ourUiBinder = GWT.create(MainUiBinder.class);
public Main() {
initWidget(ourUiBinder.createAndBindUi(this));
}
}
```
```xml
```
--------------------------------
### Using HelloWorld - instantiate and append to DOM
Source: https://www.gwtproject.org/doc/latest/DevGuideUiBinder.html
Shows how to instantiate the HelloWorld owner class and use it with direct DOM manipulation. Note that this is DOM only and will not work with GWT widgets.
```java
HelloWorld helloWorld = new HelloWorld();
// Don't forget, this is DOM only; will not work with GWT widgets
Document.get().getBody().appendChild(helloWorld.getElement());
helloWorld.setName("World");
```
--------------------------------
### Define ClientBundle with ImageResource and CssResource
Source: https://www.gwtproject.org/doc/latest/DevGuideClientBundle.html
An example of a ClientBundle interface that bundles an image and a CSS file for use with spriting.
```java
interface MyResources extends ClientBundle {
@Source("image.png")
ImageResource image();
@Source("my.css");
CssResource css();
}
```
--------------------------------
### webAppCreator command syntax
Source: https://www.gwtproject.org/doc/latest/RefCommandLineTools.html
The general syntax for invoking the webAppCreator command-line tool.
```bash
webAppCreator [-[no]overwriteFiles] [-[no]ignoreExistingFiles] \
[-templates template1,template2,...] [-out dir] \
[-junit pathToJUnitJar] [-[no]maven] [-[no]ant] moduleName
```
--------------------------------
### CSS Selector Merging Restriction Example
Source: https://www.gwtproject.org/doc/latest/DevGuideClientBundle.html
Rules cannot be merged if they define common properties to preserve semantic ordering.
```css
.a {background: green;}
.b {border: thin solid blue;}
.a {border-top: thin solid red;}
```
--------------------------------
### Configure PATH on Mac or Linux
Source: https://www.gwtproject.org/doc/latest/RefCommandLineTools.html
Update your .profile or .bash_profile to include the GWT distribution directory in your system PATH.
```bash
PATH=$PATH:/home/user/gwt-2.0.0/
export PATH
```
--------------------------------
### French Translation Properties
Source: https://www.gwtproject.org/doc/latest/DevGuideI18nPluralForms.html
Example of French pluralization rules in a properties file, where 'one' covers both 0 and 1.
```properties
cartItems=There are {0,number} items in your cart.
cartItems[one]=There is {0,number} item in your cart.
```
--------------------------------
### Create appengine-web.xml
Source: https://www.gwtproject.org/doc/latest/tutorial/appengine.html
Create this file at StockWatcher/war/WEB-INF/appengine-web.xml. Replace the placeholder with your App Engine application ID. This deployment descriptor is required by App Engine.
```xml
1
```
--------------------------------
### History Token URL Format
Source: https://www.gwtproject.org/doc/latest/DevGuideCodingBasicsHistory.html
Example of how a history token appears as a URL fragment in the browser location bar.
```text
http://www.example.com/com.example.gwt.HistoryExample/HistoryExample.html#page1
```
--------------------------------
### Command line execution of DevMode
Source: https://www.gwtproject.org/doc/latest/DevGuideCompilingAndDebugging.html
Equivalent command line execution for starting GWT development mode, specifying memory, classpath, and the module to run.
```bash
java -Xmx256M -cp "src;war/WEB-INF/classes;\gwt-2.0.0\gwt-user.jar;\gwt-2.0.0\gwt-dev.jar"
com.google.gwt.dev.DevMode -startupUrl Hello.html com.google.gwt.sample.hello.Hello
```
--------------------------------
### Example XML Email Document
Source: https://www.gwtproject.org/doc/latest/DevGuideCodingBasicsXML.html
A sample XML document representing an email message used for parsing demonstrations.
```xml
2007-05-12T12:03:55Z
Re: Flight info
I'll pick you up at the airport at 8:30. See you then!
```
--------------------------------
### Get stocks with handleError in onFailure
Source: https://www.gwtproject.org/doc/latest/tutorial/appengine.html
Calls stockService.getStocks and delegates failures to handleError(). The onSuccess method is omitted in the source.
```java
stockService.getStocks(new AsyncCallback() {
public void onFailure(Throwable error) {
handleError(error);
}
...
});
```
--------------------------------
### JUnit failure stack trace output
Source: https://www.gwtproject.org/doc/latest/tutorial/JUnit.html
Example output from a failed test run, including the AssertionFailedError and stack trace.
```text
Testsuite: com.google.gwt.sample.stockwatcher.client.StockWatcherTest
Tests run: 2, Failures: 1, Errors: 0, Time elapsed: 16.443 sec
Testcase: testSimple took 16.238 sec
Testcase: testStockPriceCtor took 0.155 sec
FAILED
Remote test failed at 172.29.212.75 / Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
expected=2.857142857142857 actual=0.2857142857142857 delta=0.0010
junit.framework.AssertionFailedError: Remote test failed at 172.29.212.75 / Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
expected=2.857142857142857 actual=0.2857142857142857 delta=0.0010
at com.google.gwt.sample.stockwatcher.client.StockWatcherTest.testStockPriceCtor(StockWatcherTest.java:38)
at com.google.gwt.sample.stockwatcher.client.__StockWatcherTest_unitTestImpl.doRunTest(__StockWatcherTest_unitTestImpl.java:7)
...
```
--------------------------------
### Create a working module for faster compilation
Source: https://www.gwtproject.org/doc/latest/DevGuideOrganizingProjects.html
A working module configuration that restricts permutations to speed up development time.
```xml
```