Obviously with a powerful tool like the GWT Designer I cannot show off all the bells and whistles in one tutorial but hopefully this grabs your attention enough to see what is possible and to experiment further.

Create a new project by going into Eclipse and from the menu select: File > New > Other. Browse through the listed options until you see WindowBuilder and expand that. Select the GWT Java Project option.

Press the Next button. For a project name give it StockWatcher.

Press the Next button. Click on the Create GWT Project checkbox and then change the Module Name to StockWatcher and the package name to com.google.gwt.sample.stockwatcher.StockWatcher

Note: Make sure the default Use Standard GWT only is selected.

Press the Finish button.

You should have a project structure that looks similar to this:

There will be some default generated code for you in the StockWatcher.java file:

I’m going to get rid of the Hello World boilerplate code and button. Click on the Design tab at the bottom of the source file editor and GWT Designer will render a visual layout of the current page. If you don’t see the Design tab, right-click on the Java class and select: Open With > WindowBuilder Editor.

You will see the visual representation of the page like so:

When you’re in Design mode, you should see the Designer’s Palette that lists all the supported Panels and Widgets and the Properties pane for editing widget properties. Remove the button by clicking on the Click me! button and press delete on your keyboard.

Save the project and then click on the Source tab and you’ll notice that the generated Hello World code is now gone.

Before we get into designing the UI there is something we will set to make things a little easier/cleaner. Go into the menu and select: Window > Preferences and go into the WindowBuilder and pick Code Generation. Now select the Local tab and check the Declare variable as “final” and then select the Field tab and check the Prefix field access with “this”. Press the Apply button and exit out of the preferences window.

The first thing now to get the UI under way is to go back into the Design tab. From there I’m going to select a VerticalPanel (just click on it) and drop it onto the root panel/content area by clicking on that.

Lets make the vertical panel consume the content area by dragging out the width and height to fill the available space.

I’m going to update the vertical panel’s variable name to something else. Click on the verticalPanel in the Components section and then in the properties set the Variable property to mainPanel.

Several more things need to get added and the way we do this is the same way I just did with the VerticalPanel. Repeat these steps for the following (in the order as they appear below):

1. Add a FlexTable inside of the existing VerticalPanel.
2. Change the FlexTable’s variable name to stocksFlexTable
3. Add a HorizontalPanel below the FlexTable
4. Change the HorizontalPanel’s variable name to addPanel
5. Add a TextBox inside of the HorizontalPanel
6. Give the TextBox a variable name of newSymbolTextBox
7. Set the TextBox’s Focus property to true
8. Add a Button beside the TextBox on the right-hand side of the TextBox)
10. Change the Button’s variable name to addButton
11. Change the Button’s text property to Add
12. Add a Label below the HorizontalPanel
13. Change the Label’s variable name to lastUpdatedLabel

Your layout should look like this:

The structure should look like this:

Save the file.

If you go into the StockWatch.java file and look at the source code you’ll see something similar to this:

Assuming everything is done correctly you can run this project to see what it looks like so far. Right-click on the project and select: Run as > Web Application

You can choose the Launch Default Browser button and see the results.

Result:

Well its ugly… Don’t worry we can fix that later because right now I’m going to wire up some events. In fact I’ll be adding two events. One will add a listener when the button is clicked and another one will listen for when a keydown event is triggered in the textbox.

Go beck into Design view and click on the TextBox. We will now learn another way to add events (keep in kind you could create this event the same way I did with the button). Inside the Properties click on the Show Events button.

Go into the: keyPress > onKeyPress and double click and the code will be added for us and just like before we will be dropped into the code for the event handler.

Add the same call to addStock but this time I also want to check to ensure the key that was pressed is the Enter key and nothing else:

Update (June 13, 2012): I’ve been informed by a reader that the KeyPressHandler to register the Enter key might not work in FireFox. In that case you might want to try the KeyDownHandler instead. I have not verified this.

Note: Depending on your Eclipse configuration, it might create the addStock method with an access modifier of protected. Since I’m not going to subclass StockWatcher I’ll change it’s access from protected to private.

Now that we’ve created the addStock function we need to add some code into it. In this function I’m going to add some basic code to help determine what the user types is as valid as possible. Here is the code I’m going to use:

private void addStock() {
final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
newSymbolTextBox.setFocus(true);
// Stock code must be between 1 and 10 chars that are numbers, letters, or dots.
if (!symbol.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + symbol + "' is not a valid symbol.");
newSymbolTextBox.selectAll();
return;
}
newSymbolTextBox.setText("");
// TODO Don't add the stock if it's already in the table.
// TODO Add the stock to the table.
// TODO Add a button to remove this stock from the table.
// TODO Get the stock price.
}

Save and run the project again just like before. Type in some invalid characters into the textbox and press the enter key in the textbox or press the add button.

Note: Keep in mind in a real GWT production app you not only need to validate the input from the user on the client but on the server as well. Don’t trust any data that is only validated on the client!

I’m going to finish off the last bit of code now to actually add the stock to the Stock Watcher. I’ll use the ArrayList so you will need to add an import:

import java.util.ArrayList;

Note: With Eclipse you typically get a red squiggle under an unknown object, hovering over that will give you options to import.

Create an ArrayList variable now just below with the other class variables:

Now I’m going to add a new class called StockPrice. Right-click on the com.google.gwt.sample.stockwatcher.client package and choose: File > New > Class. Ensure the class name is StockPrice. The rest of the defaults should be fine so just press Finish.

What I want to do now is populate an array of StockPrice objects with some values and pass them onto a function that will update the FlexTable. Time to finish the refreshWatchList function with the following code:

Save and run the project. Add some stocks and notice how they get updated automatically now.

Well its still ugly so its almost now time to use the GWT Designer’s support for CSS however before I get to that lets add the logo for the Stock Watcher.

The first thing I did was right-click on the src folder and added a new package called images. You can put this images folder wherever you want, I’m simply putting it somewhere easy to access for the sake of simplicity. Right-click the image below and save it to a folder of your choice on your computer.

Right-click on src/images and choose import from the menu. Then in the import window choose: General > File System and browse to where you saved the logo and import it.

Make sure your in the StockWatcher.java file and click on the Design tab. Click on the Image widget and put one just above the FlexTable. In the properties for the new image make sure the variable name is set to logoImage.

I’m going to also add another Label widget to hold the title of the Stock Watcher app. Add a label right below the image. Set the label’s text property to Stock Watcher. Your structure should look like this:

I’m going to populate the image using a ClientBundle but first lets style this application.

Go to the newly added Stock Watcher label’s properties and select the styleName property and click on the small css button on the right hand side. The CSS Style Editor window opens. Click the Add… button and change the default style name to .gwt-Label-StockWatcher. Press OK to close the dialog.

While still in the CSS Style Editor press the Edit… button. Set the size to 18 and the weight to bold and then press Ok to close the CSS Rule Editor. Close the CSS Style Editor now by pressing OK.

The resulting CSS will look like this:

gwt-Label-StockWatcher {
font-size: 18px;
font-weight: bold;
}

Another way to get into the CSS Style Editor is to right-click on the StockWatcher.css file and select: Open With > CSS Editor

Notice now at the bottom of the StockWatcher.css class you can choose between a Source and Design tab. Click on each of those.

The last thing that needs to be done is to get the logo into the Image widget I added earlier. For this I’m going to use a ClientBundle. Right-click on the com.google.gwt.sample.stockwatcher.StockWatcher.client package and select: New > ClientBundle. Name the new class Resources.

thanks for the tutorial, why not add some information about how to retrieve the real stock price using RequestBuilder, ( i believe there is some web service abvailable free for that), this might be really much more helpful as lots of people are looking for ways to resolve the GWT SOP issue

Is it an oversight on your part or is it not needed as the docs say it is or is it because of something else altogether? As the tutorial works without it I am guessing that it isn’t needed but then why would the docs say it is?

I was able to implement the RPC using the code from this tutorial’s refreshWatchList method in my StockPriceServiceImpl which I passed the stocks ArrayList as a parameter. I also had to change com.google.gwt.user.client.Random to a java.util.Random and instantiate it but that was it. Very straight forward and intuitive.

I used the GWT Designer’s tooling in Eclipse to generate the boilerplate interfaces for the client and the implementation class for the server. The tooling also maintained the web.xml config file for me adding the proper servlet definitions.

I am very impressed with GWT & Designer and after I get a little more exposure to both I intend to begin a conversion of a rather large App Engine project that is written in Groovy.

Do you have a sense for how popular GWT is becoming in the JAVA EE community? I mean, is there a possibility that GWT will eventually be the choice over straight Javascript in the development community? I ask because I want to invest my time wisely in working with new technologies and hopefully invest in those that have a future and broad appeal.

I can really only comment on the traffic to this blog with regards to GWT’s popularity and my own personal experience so take that with a grain of salt. The GWT topics are some of the most popular for my blog according to my stats. I don’t think GWT is a good fit for every Java web project out there but it could probably be a good fit for many of them – it all depends. Investing in JavaScript is something that I don’t think anyone will regret especially since JQuery is such a huge player in the world now and with things like NodeJS picking up steam a solid foundation in JavaScript is becoming more and more critical. Even with GWT you will find it doesn’t do everything for you and the time will come when you need to use GWT JSNI. I’d learn GWT, but at the same time I’d keep learning JavaScript along with JQuery and some Spring knowledge wouldn’t hurt as well if you are going down the Java road. GWT won’t ever replace the need know JavaScript in my opinion.

Personally I keep a close eye on almost everything out there so I have some knowledge about each. I focus on specific technologies though when it is time to do a project. A current project I’m working on is using JQuery Mobile with PHP (on Ubuntu). It could have been done in GWT but I found the mobile support better for the requirements to be built with JQuery Mobile. I have other projects though that I used GWT for, it just depends on the requirements really what tool is best for the task.

One more question. If I start an application using GWT, and then later on decide that I want to just use Javascript because it gives more more flexibility, is it possible to do that without having to rewrite everything?

You can always use your own custom JavaScript with GWT via JSNI. Its all going to come down to your project’s requirements. If you start a project you want to make sure what you choose to use will support the given requirements. Example: Does GWT (or Vaadin) have the widgets you want? Does JQuery UI? Whats easier for you to work with? How much flexibility might you need?

I wish it was that easy for us, but our requirements are constantly changing, hence I need a crystal ball to know what tools I should use. Ideally, I’d like to start with the easiest approach, as long as I can migrate to something more flexible as needed. Sounds like GWT gives you that ability.