void main(){BenjaminCoe.com();}

A Code Master's Handbook

GWT Basics a Practical Tutorial 

As I mentioned in my first blog post, I used Google Web Toolkit for the menus and some of the layout on this site. I thought I would post a quick and, I hope, useful tutorial on how to add this functionality to your own website. The technology is even more useful when used to tie your website into a web-service back-end, but this is beyond what I needed it for for my personal site (I just wanted nice cross-platform Javascript widgets).


As I started typing up this tutorial, I immediately noticed that the [code] tags in the blogging software I have installed (Simple PHP Blog) look quite terrible. I quickly sat down and spliced Generic Syntax Highlighting into the library. You can now leave code related comments using the tag [code language=java,php,etc]. Let me know if there's any interest in me posting information about how I went about this little hack.


So, let's get started. This tutorial will show you how to:
  1. Use a couple basic controls in GWT.
  2. Use two different types of event interfaces in GWT.
  3. Make a Youtube video pop-up (handy for just about any website.)
  4. Use a panel for layout.


Below is what the finished product will be:


Step 1: Downloading GWT/Related Software
First of all, you will need to install the GWT software, which can be found here. You will also need ant, and a Java Development Environment setup. If you so please, you might try using a development environment like Eclipse, but I'm more of a command line kind of guy.

Step 2: Creating a Project
GWT provides the command line tool webAppCreator for creating a project. For this tutorial I created a project using this command:

./webAppCreator -out example com.bencoe.example

This creates a folder called 'example'. This folder contains all the files we will be editing.

Step 3: HTML/CSS
If we look in 'example/war/' we can note two files example.css and example.html. These files are not re-created when we run ant, and are where we can make changes to our website's style and layout.

For this tutorial I edited the HTML in example.html to look like this:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- The HTML 4.01 Transitional DOCTYPE declaration-->
<!-- above set at the top of the file will set     -->
<!-- the browser's rendering engine into           -->
<!-- "Quirks Mode". Replacing this declaration     -->
<!-- with a "Standards Mode" doctype is supported, -->
<!-- but may lead to some differences in layout.   -->

<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <!--                                                               -->
    <!-- Consider inlining CSS to reduce the number of requested files -->
    <!--                                                               -->
    <link type="text/css" rel="stylesheet" href="example.css">

    <!--                                           -->
    <!-- Any title is fine                         -->
    <!--                                           -->
    <title>Web Application Starter Project</title>
    
    <!--                                           -->
    <!-- This script loads your compiled module.   -->
    <!-- If you add any GWT meta tags, they must   -->
    <!-- be added before this line.                -->
    <!--                                           -->
    <script type="text/javascript" language="javascript" src="example/example.nocache.js"></script>
  </head>

  <!--                                           -->
  <!-- The body can have arbitrary html, or      -->
  <!-- you can leave the body empty if you want  -->
  <!-- to create a completely dynamic UI.        -->
  <!--                                           -->
  <body>

    <!-- OPTIONAL: include this if you want history support -->
    <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>

    <h1>Ben's GWT Example</h1>

	<div id="examplePanel" />
  </body>
</html>



The important thing to note is the div with the id examplePanel this is where the panel I create in this tutorial will be inserted.

Step 3: The Java Code
GWT converts code you make in Java into cross-browser Javascript. The code we will be editing can be found in example/src/com/bencoe/client/example.java. The example they provide you with involves a web-service, you would need to install Tomcat and deploy the war file to use this. Just delete the contents of example.java we will be making a simpler application.

Here's the code with comments:

  
  
/**
A simple example of using GWT to make a couple cool GUI components for a website.

Benjamin E. Coe (2009).

*/

package com.bencoe.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.*;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class example implements EntryPoint {

The only thing important to note here is that we import a bunch of GUI/Event-Handling libraries and implement the EntryPoint interface. This will let this class be used as the main entry-point for our GWT application.
	
	//Used to generate a video pop-up event.
	private static class videoCommand implements Command,ClickListener{
		private String video="";
		
		//Constructor.
		public videoCommand(String video){
			this.video=video;
		}
		
		public void execute(){
			new VideoDialog(video).show();
		}

		public void onClick(Widget sender){
			new VideoDialog(video).show();
		}
	}


This internal class is used to pop-up our Youtube videos. It implements the Command interface, which allows instances of this class to handle menu events, and also the ClickListener interface, which allows it to handle clicks from the mouse. When either of these events fires (execute or onClick), we create an instance of our VideoDialog class.

    

	//Create video commands for both the videos I use in this example.
	videoCommand portfollioVideo=new videoCommand("<object width=\"425\" height=\"344\"><param name=\"movie\" value=\"http://www.youtube.com/v/dKQRAGghfH0&hl=en&fs=1&\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"http://www.youtube.com/v/dKQRAGghfH0&hl=en&fs=1&\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"425\" height=\"344\"></embed></object>");

	videoCommand wikiearthVideo=new videoCommand("<object width=\"560\" height=\"340\"><param name=\"movie\" value=\"http://www.youtube.com/v/HsyHecofNHw&hl=en&fs=1&\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"http://www.youtube.com/v/HsyHecofNHw&hl=en&fs=1&\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"560\" height=\"340\"></embed></object>");


Here we create two instances of the videoCommand class, one for each of the videos that our GUI can pop-up.

    

	//This class actually displays the video.
	private static class VideoDialog extends PopupPanel {
		
		public VideoDialog(String video) {
			HTML youtubeHTML=new HTML(video);
			
			Button ok = new Button("Close Video");
			ok.addClickListener(new ClickListener() {
								public void onClick(Widget sender) {
								VideoDialog.this.hide();
								}
								});
			
			VerticalPanel panel = new VerticalPanel();
			panel.add(youtubeHTML);
			panel.add(ok);
			setWidget(panel);
			
			this.center();
		}
	}


This is the internal class that actually pops up our Youtube video, it is instantiated from our instances of videoCommand and the specific video is passed in via the constructor. The code does the following:
  • Creates an HTML widget from the Youtube video passed into the constructor.
  • Creates a button widget with a ClickListener. This will hide the video when the button is pressed.
  • Creates a VerticalPanel and adds both the widgets to it.
  • Centers the widget on the screen.

    
	
	/**
	 Create the menu GUI component and return it.
	 */
	MenuBar createMenu(){		
		//The top-level of our example menu.
		MenuBar exampleMenu = new MenuBar(true);

		//The sub-menu for the videos.
		MenuBar videos = new MenuBar(true);
		videos.addItem("<a style=\"color:black;text-decoration:none;\" >Portfollio Video</a>",true,portfollioVideo);
		videos.addItem("<a style=\"color:black;text-decoration:none;\" >Wikiearth Video</a>",true,wikiearthVideo);

		//Add our sub-menu to the parent menu item.
		exampleMenu.addItem("Videos", videos);

		//Add all the menus to our top-level menu-bar.
		MenuBar menu = new MenuBar();
		menu.addItem("Example Menu", exampleMenu);

		return(menu);
	}


This code creates our pull-down menu widget. Basically we can recursively add menu items or other menus into the MenuBar objects (creating a multi-level menu). Note that while adding the menu items we can pass in classes implementing the Command interface. When these menu items are clicked the execute() method of these classes will be fired. In this case, clicking on 'Portfollio Video' and 'Wikiearth Video' respectively, will cause our classes to execute and pop-up a video.

    

	/**
	 Create a tree menu.
	 */
	public Tree createTree(){
		TreeItem exampleTree = new TreeItem("Example Tree");
		TreeItem videosNode = new TreeItem("Videos");
		
		exampleTree.addItem(videosNode);
		
		//Create the video labels.
		Label portfollioLabel=new Label("Portfollio Video");
		portfollioLabel.addClickListener(portfollioVideo);
		Label wikiearthLabel=new Label("Wikiearth Label");
		wikiearthLabel.addClickListener(wikiearthVideo);
		
		videosNode.addItem(portfollioLabel);
		videosNode.addItem(wikiearthLabel);
		
		Tree returnMe=new Tree();
		returnMe.addItem(exampleTree);
		
		return(returnMe);
	}


This creates our tree widget in a manner similar to our pull-down menu. However, we instead attach a click listener to the menu items. This will have the same ultimate effect, but will call the onClick method in our class instead.

    
	/**
	 Create all the GUI components for this small tutorial.
	 */
	public void createGUI(){
		MenuBar menu=createMenu();
		Tree tree=createTree();

		//Create a panel for adding our components to.
		HorizontalPanel MyHorizontalPanel=new HorizontalPanel();
		
		//Add our menu to the horizontal panel.
		MyHorizontalPanel.add(menu);
		MyHorizontalPanel.add(tree);

		RootPanel.get("examplePanel").add(MyHorizontalPanel);
		RootPanel.get("examplePanel").setStylePrimaryName("examplePanel");
	}

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		createGUI();
	}
}


The remaining code does the following:
  • onModuleLoad() is the main entry point for the application. Upon executing it simply calls the method that creates our GUI.
  • In createGUI() our pull-down menu and tree-menu are created.
  • A new horizontal panel is created and both the components are added in (this means the components will be aligned left to right).
  • Using the static class RootPanel, we fetch the div we previously added into our HTML 'examplePanel'. The ids we have access to via RootPanel correspond directly with the div ids in our example.html file. Add is used, to insert the horizontal panel we just created into the body of our HTML document.

Step 4: Compiling our Code
From the directory example/ simply type ant. Once ant finishes running, you should now be able to open up example/war/example.html and have a working application.

So there you have it, let me know how you find the tutorial. I'll certainly post more when I'm extremely bored/procrastinating.

------------------------
Benjamin E. Coe
Procrastination-Expert

[ 2 comments ] ( 41 views ) permalink

<<First <Back | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | Next> Last>>

Valid XHTML 1.0 Transitional
© 2009 Benjamin E. Coe