文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Building a Tag-Cloud Using the Google Web Toolkit

Building a Tag-Cloud Using the Google Web Toolkit

时间:2009-04-05  来源:cobrawgl

A while back, I read a tutorial by Dan Wellman, which described the steps required to produce a neat Tag-Cloud. Dan's example largely relied on the jQuery framework to request data and construct the user interface elements. I decided to write his tutorial all over again with the two exceptions of using GWT instead of jQuery, and a different method of choosing font size variations.

Author: Arman Mirkazemi

This is a NETTUTS contributor who has published 1 tutorial(s) so far here. Their bio is coming soon!

In case you don't know what Tag-Clouds are and what purpose they serve, briefly, a Tag-Cloud is a form of visualizing the difference in importance or activeness of some predefined categories based on how large they appear in the cloud.

We are going to use the latest version of GWT (currently 1.5) and work with MySQL and PHP as our back-end to request the JSON data. Similar to Dan's tutorial, I too, assume that you already are familiar with inserting into a database. The PHP code in this article will merely cover how to query data from the database and send back the result in JSON format. You should expect to learn:

  • how GWT can request data from a PHP back-end and handle the response using callbacks
  • how to use PHP to send JSON data back to the GWT client
  • how to parse JSON data in GWT
  • how to create and place a couple of GWT user interface widgets
  • how to stylize GWT widgets using CSS
  • how to choose a good font size variation for the tag-cloud

I used the Cypal Studio GWT plug-in for Eclipse to create this project. If you are already using this combination, you should be able to download and open this project in Eclipse. Otherwise here is a link to obtain more information.

Although GWT debugger doesn't exactly debug JavaScript, using Eclipse with Cypal Studio plug-in allows for debugging GWT code inside the Eclipse IDE, which is better than many other JavaScript debuggers out there.

Let's Get Started

By default, as part of the script that generates a blank GWT project, you will get an HTML file which, more or less, looks like the code below. You may need to correct the path of the JavaScript file according to your server setup.

view plaincopy to clipboardprint?
  1. <html>    
  2.     <head>    
  3.         <title>Main</title>    
  4.     </head>    
  5.     <body>    
  6.         <script language="javascript" src="in.cypal.studio.gwt.samples.TagCloud.nocache.js"></script>    
  7.        
  8.         <!-- This div is added to allow center align the page even in IE  -->  
  9.         <div id="wrapper" style="text-align:center"></div>  
  10.     </body>    
  11. </html>  
<html> <head> <title>Main</title> </head> <body>  <!-- This div is added to allow center align the page even in IE --> <div id="wrapper" style="text-align:center"></div> </body> </html> 

Our tag cloud is going to appear in the center of the browser. Since center-aligning pages using CSS doesn't work properly in IE, we add a new DIV element and set its id to "wrapper". This is all we need to get started. As we move further in this tutorial, we will re-visit this document to add more, but for now let's move on.

Requesting JSON Data

We will start by modifying the onModuleLoad() method of the MainEntryPoint class, as it's the method that GWT uses to begin executing our code. We want to start by requesting data (tag names and their frequencies) from the PHP and MySQL back-end.

view plaincopy to clipboardprint?
  1. public void getTagData(){    
  2.        
  3.     // you may need to change the URL according to your server setup   
  4.     String url = "/wmGetTags.php";     
  5.        
  6.     RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET,url);    
  7.     try{    
  8.         requestBuilder.sendRequest(null, new RequestCallback() {    
  9.             public void onResponseReceived(Request request, Response response){    
  10.                 if (response.getStatusCode() == 200){    
  11.                     // handler code   
  12.                 }    
  13.             }    
  14.                
  15.             public void onError(Request request, Throwable exception){    
  16.                 throw new UnsupportedOperationException("Not supported yet.");    
  17.             }    
  18.         });    
  19.     } catch (Exception e){    
  20.         e.printStackTrace();    
  21.     }    
  22. }    
  23.   
  24. public void onModuleLoad() {    
  25.   
  26. }  
public void getTagData(){ // you may need to change the URL according to your server setup String url = "/wmGetTags.php"; RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET,url); try{ requestBuilder.sendRequest(null, new RequestCallback() { public void onResponseReceived(Request request, Response response){ if (response.getStatusCode() == 200){ // handler code } } public void onError(Request request, Throwable exception){ throw new UnsupportedOperationException("Not supported yet."); } }); } catch (Exception e){ e.printStackTrace(); } } public void onModuleLoad() { } 

We have defined a new method called getTagData() in which the RequestBuilder type is instantiated to call the wmGetTags PHP script in the back-end. Note how the sendRequest() method takes in a callback parameter that handles the response once it arrives back.

When creating a new RequestCallback, we must implement the onResponseReceived() and onError() methods to handle each case. Notice how in the onResponseReceived() method, we check the response status code. This is because during the life cycle of a request, this method could be invoked multiple times by the browser even though it may not be completely fulfilled. A request is complete only when the status code is equal to 200. We check the status code using the getStatusCode() method.

Next we will create a FlowPanel widget and insert it inside the "wrapper" DIV. The GWT widget library provides many different kinds of panels for different use; however, a FlowPanel is the kind of widget that allows for holding more than one child widget in itself. This property makes it a suitable widget for a Tag-Cloud. What we are doing here is creating a holding container for all the tags that we must show.

view plaincopy to clipboardprint?
  1. public void onModuleLoad() {    
  2.     getTagData();    
  3.     flowPanel = new FlowPanel();    
  4.     RootPanel.get("wrapper").add(flowPanel);    
  5. }  
public void onModuleLoad() { getTagData(); flowPanel = new FlowPanel(); RootPanel.get("wrapper").add(flowPanel); } 

Constructing a Response Using PHP

This part is fairly simple. Let's create a new PHP script and call it wmGetTags.php. First, we must create a connection to the database using the mysql_connect() function, then perform a SELECT query on the table that holds both tag names and their occurrences. Finally when the query is done, we use a "For Loop" to generate a JSON formatted response.

<?php //connection information $host = "localhost"; $user = "root"; $password = "your_password_here"; $database = "tagcloud"; //make connection $server = mysql_connect($host, $user, $password); $connection = mysql_select_db($database, $server); //query the database $query = mysql_query("SELECT * FROM tags"); //start json object $json = "(["; //loop through and return results for ($x = 0; $x < mysql_num_rows($query); $x++) { $row = mysql_fetch_assoc($query); //continue json object $json .= "{tag:'" . $row["tag"] . "',frequency:" . $row["frequency"] . "}"; //add comma if not last row, closing brackets if is if ($x < mysql_num_rows($query) -1) $json .= ","; else $json .= "])"; } //return JSON with GET for JSONP callback $response = $_GET["callback"] . $json; echo $response; //close connection mysql_close($server); ?> 

When executed, the script above will generate a response similar to that shown below:

([{tag:'Gmail',frequency:21},{tag:'Web',frequency:19},{tag:'Salesforce',frequency:66},{tag:'Amazon',frequency:17}]) 

Above is an example of a JSON response. To be precise, this will be parsed into an array with each of its four indexes holding an object with two fields. The first field "tag" holds the name of the tag, while the second field "frequency" holds the occurrences count. Running what we've coded so far will produce a blank page, however inspecting browser communications using the "Net" tab in Firebug should show us the output of the PHP script above like shown in the image below.

Parsing JSON Data

At this point we must define the routine that will parse the response received from the back-end and construct the UI further to show the tags in the cloud. Since the HTTP and JSON types are contained within separate GWT modules, we must add the following <inherits> tags to our <module name>.gwt.xml to ensure the code needed to parse JSON is included for runtime:

<inherits name="com.google.gwt.json.JSON" /> <inherits name="com.google.gwt.http.HTTP" /> 

You can find more about GWT modules here.

view plaincopy to clipboardprint?
  1. public void getTagData(){    
  2.   
  3.     // ...    
  4.   
  5.     try{    
  6.         requestBuilder.sendRequest(null, new RequestCallback() {    
  7.             public void onResponseReceived(Request request, Response response){    
  8.                 if (response.getStatusCode() == 200){    
  9.                     handleGetTags(response.getText());    
  10.                 }    
  11.             }    
  12.            
  13.             public void onError(Request request, Throwable exception){    
  14.                 throw new UnsupportedOperationException("Not supported yet.");    
  15.             }    
  16.         });    
  17.     } catch (Exception e){    
  18.             e.printStackTrace();    
  19.     }    
  20. }  
public void getTagData(){ // ... try{ requestBuilder.sendRequest(null, new RequestCallback() { public void onResponseReceived(Request request, Response response){ if (response.getStatusCode() == 200){ handleGetTags(response.getText()); } } public void onError(Request request, Throwable exception){ throw new UnsupportedOperationException("Not supported yet."); } }); } catch (Exception e){ e.printStackTrace(); } } 

We now must call the handleGetTags() when the status code of the Response instance is equal to 200 like shown in the above code. The handleGetTags() method will actually process the JSON data.

view plaincopy to clipboardprint?
  1. public void handleGetTags(String jsonText){    
  2.     
  3.     JSONObject jsonObject;    
  4.     JSONString tagName;    
  5.     JSONNumber tagFreq;    
  6.     int frequency;    
  7.     String realTagName;    
  8.        
  9.     JSONValue jsonValue = JSONParser.parse(jsonText);    
  10.     JSONArray jsonArray = jsonValue.isArray();    
  11.        
  12.     if (jsonArray != null){    
  13.         for (int i = 0; i < jsonArray.size(); i++){    
  14.              jsonObject = (JSONObject)jsonArray.get(i);    
  15.              tagName = jsonObject.get("tag"      ).isString();    
  16.              tagFreq = jsonObject.get("frequency").isNumber();    
  17.              frequency = (int)tagFreq.doubleValue();    
  18.              Hyperlink tagLink = new Hyperlink(tagName.stringValue(),tagName.stringValue());    
  19.              flowPanel.add(tagLink);    
  20.         }    
  21.     }    
  22. }   
public void handleGetTags(String jsonText){ JSONObject jsonObject; JSONString tagName; JSONNumber tagFreq; int frequency; String realTagName; JSONValue jsonValue = JSONParser.parse(jsonText); JSONArray jsonArray = jsonValue.isArray(); if (jsonArray != null){ for (int i = 0; i < jsonArray.size(); i++){ jsonObject = (JSONObject)jsonArray.get(i); tagName = jsonObject.get("tag" ).isString(); tagFreq = jsonObject.get("frequency").isNumber(); frequency = (int)tagFreq.doubleValue(); Hyperlink tagLink = new Hyperlink(tagName.stringValue(),tagName.stringValue()); flowPanel.add(tagLink); } } } 

All XMLHTTPRequest communication between the client and the back-end happens through plain text. So even though the back-end response is JSON formatted, it's yet to be converted/parsed into real JavaScript objects that we can then interact with, as shown below.

  1. JSONValue jsonValue = JSONParser.parse(jsonText);   
  2. JSONArray jsonArray = jsonValue.isArray();   
JSONValue jsonValue = JSONParser.parse(jsonText); JSONArray jsonArray = jsonValue.isArray(); 

The JSONParser class provides a static method called parse() that takes in a String parameter and returns a JSONValue object that we can then interact with. As we previously established, our PHP script will return an array structure holding a number of objects encapsulating data related to the tags. To get a handle to that array we must use the isArray() method.

view plaincopy to clipboardprint?
  1. for (int i = 0; i < jsonArray.size(); i++){    
  2.        
  3.     jsonObject = (JSONObject)jsonArray.get(i);    
  4.     tagName = jsonObject.get("tag"      ).isString();    
  5.     tagFreq = jsonObject.get("frequency").isNumber();    
  6.     frequency = (int)tagFreq.doubleValue();    
  7.     realTagName = tagName.stringValue();    
  8.     
  9.     //...   
  10.      
  11. }  
for (int i = 0; i < jsonArray.size(); i++){ jsonObject = (JSONObject)jsonArray.get(i); tagName = jsonObject.get("tag" ).isString(); tagFreq = jsonObject.get("frequency").isNumber(); frequency = (int)tagFreq.doubleValue(); realTagName = tagName.stringValue(); //... } 

The above code will access the embedded object within every index of the array to get to the actual tag data. So in every iteration of the loop, content of the current index is returned as a JSONObject. Every extracted JSONObject should have two fields: tag, and frequency. We use the get() method of JSONObject class to retrieve these fields.

view plaincopy to clipboardprint?
  1. Hyperlink tagLink = new Hyperlink(tagName.stringValue(),null);    
  2. flowPanel.add(tagLink);  
Hyperlink tagLink = new Hyperlink(tagName.stringValue(),null); flowPanel.add(tagLink); 

Next we must inject the tag names into the cloud UI. Remember the FlowPanel that we created earlier? We now want to create hyperlink widgets and insert them into our flow panel - that is what these two lines above are doing. If we run the project, our tag-cloud should look like this:

Stylizing Widgets

At this point we have what appears to be a list of links - but nothing like a tag-cloud yet. GWT lets the developer precisely control the way that each widget renders by allowing the developer to provide his own CSS. That is what we must do to give our tag-cloud a face lift. Let's go back to our HTML again.

view plaincopy to clipboardprint?
  1. <html>    
  2.     <head>    
  3.         <title>Main</title>    
  4.         <style>    
  5.             * {    
  6.                 padding : 0;    
  7.                 margin : 0;    
  8.                 font-family : "Lucida Grande","Lucida Sans Unicode",Arial,Verdana,sans-serif;    
  9.                 overflow : hidden;    
  10.             }    
  11.                
  12.             .cloudWrap {    
  13.                 text-align : center;    
  14.                 margin : 50px auto;    
  15.                 background-color : #333;    
  16.                 padding : 10px;    
  17.                 width : 400px;    
  18.                 line-height : 1.5em;    
  19.             }    
  20.                
  21.             .cloudTags {    
  22.                 float : left;    
  23.                 padding : 5px;    
  24.             }    
  25.                
  26.             .cloudTags a {    
  27.                 color : #FFFFFF;    
  28.                 text-decoration : none;    
  29.             }    
  30.         </style>    
  31.     </head>    
  32.     <body>    
  33.         <script language="javascript" src="in.cypal.studio.gwt.samples.TagCloud.nocache.js"></script>    
  34.   
  35.         <!-- This div is added to allow center align the page even in IE  -->  
  36.         <div id="wrapper" style="text-align:center"></div>  
  37.     </body>    
  38. </html>  
<html> <head> <title>Main</title> <style> * { padding : 0; margin : 0; font-family : "Lucida Grande","Lucida Sans Unicode",Arial,Verdana,sans-serif; overflow : hidden; } .cloudWrap { text-align : center; margin : 50px auto; background-color : #333; padding : 10px; width : 400px; line-height : 1.5em; } .cloudTags { float : left; padding : 5px; } .cloudTags a { color : #FFFFFF; text-decoration : none; } </style> </head> <body>  <!-- This div is added to allow center align the page even in IE --> <div id="wrapper" style="text-align:center"></div> </body> </html> 

The first CSS rule above resets the padding and margin values and then sets the font for our tag-cloud. The latter rules define how each of the tags should be positioned so that they appear one after another in a horizontal fashion with the line height, padding and so forth.

Now you might ask the question: "But how do we tell GWT which CSS class to use for what widget?" Well, that's easy. Every widget from the GWT UI library provides a method called setStylePrimaryName() that takes in the name of the CSS class that you want to assign to the widget. Now, we must go back and assign the correct CSS classes to our widgets. There are two places where we need to do this. The first is the FlowPanel that holds the tags.

view plaincopy to clipboardprint?
  1. public void onModuleLoad() {    
  2.     getTagData();    
  3.     flowPanel = new FlowPanel();    
  4.     flowPanel.setStylePrimaryName("cloudWrap");    
  5.     RootPanel.get().add(flowPanel);   
  6. }  
public void onModuleLoad() { getTagData(); flowPanel = new FlowPanel(); flowPanel.setStylePrimaryName("cloudWrap"); RootPanel.get().add(flowPanel); } 

The second is after adding a hyperlink to the FlowPanel.

view plaincopy to clipboardprint?
  1. Hyperlink tagLink = new Hyperlink(tagName.stringValue(),null);    
  2. flowPanel.add(tagLink);    
  3. tagLink.setStylePrimaryName("cloudTags");  
Hyperlink tagLink = new Hyperlink(tagName.stringValue(),null); flowPanel.add(tagLink); tagLink.setStylePrimaryName("cloudTags"); 

We now should have something that looks similar to this:

Setting the Font Size

As you can see, our tags have come through and it looks more like a tag-cloud. Next we must set the size of each tag to appear according to its number of occurrences.

The simplest implementation is to use a linear function to map a tag's frequency of use to its font size in the tag-cloud. The algorithm used for deciding the font size evaluates the frequency of every tag against the smallest occurrence and the largest occurrence, and then returns a font size within the range of the smallest and largest font size that we define.

So first we must find the tags with the smallest and largest number of frequency and remember them within the class variables minFrequency and maxFrequency. We have also identified the smallest and largest font size by setting the MIN_FONT_SIZE and MAX_FONT_SIZE final variables.

view plaincopy to clipboardprint?
  1. int maxFrequency = 0;    
  2. int minFrequency = 600000000;    
  3. final int MIN_FONT_SIZE = 5;    
  4. final int MAX_FONT_SIZE = 25;    
  5.   
  6. public void handleGetTags(String jsonText){    
  7.   
  8.     // ...    
  9.   
  10.     for (int i = 0; i < jsonArray.size(); i++){    
  11.         jsonObject = (JSONObject)jsonArray.get(i);    
  12.         tagFreq = jsonObject.get("frequency").isNumber();    
  13.         frequency = (int)tagFreq.doubleValue();    
  14.         if (minFrequency > frequency)    
  15.             minFrequency = frequency;    
  16.         if (maxFrequency < frequency)    
  17.             maxFrequency = frequency;    
  18.     }    
  19.        
  20.     // ...    
  21. }  
int maxFrequency = 0; int minFrequency = 600000000; final int MIN_FONT_SIZE = 5; final int MAX_FONT_SIZE = 25; public void handleGetTags(String jsonText){ // ... for (int i = 0; i < jsonArray.size(); i++){ jsonObject = (JSONObject)jsonArray.get(i); tagFreq = jsonObject.get("frequency").isNumber(); frequency = (int)tagFreq.doubleValue(); if (minFrequency > frequency) minFrequency = frequency; if (maxFrequency < frequency) maxFrequency = frequency; } // ... } 

Next, we define a method called getLabelSize() which takes in the frequency for the current tag and returns the CSS font-size for that tag.

view plaincopy to clipboardprint?
  1. public String getLabelSize(int frequency){    
  2.     double weight = (Math.log(frequency) - Math.log(minFrequency)) / (Math.log(maxFrequency) - Math.log(minFrequency));    
  3.     int fontSize = MIN_FONT_SIZE + (int)Math.round((MAX_FONT_SIZE - MIN_FONT_SIZE) * weight);    
  4.     return Integer.toString(fontSize) + "pt";    
  5. }  
public String getLabelSize(int frequency){ double weight = (Math.log(frequency) - Math.log(minFrequency)) / (Math.log(maxFrequency) - Math.log(minFrequency)); int fontSize = MIN_FONT_SIZE + (int)Math.round((MAX_FONT_SIZE - MIN_FONT_SIZE) * weight); return Integer.toString(fontSize) + "pt"; } 

Now we must individually assign the CSS font-size to each hyperlink widget that we add to the FlowPanel. To do so, we must get a handle to the Style object of the hyperlink element and set the fontSize property as shown below:

view plaincopy to clipboardprint?
  1. Style linkStyle = tagLink.getElement().getStyle();    
  2. linkStyle.setProperty("fontSize",getLabelSize(frequency));  
Style linkStyle = tagLink.getElement().getStyle(); linkStyle.setProperty("fontSize",getLabelSize(frequency)); 

And our MainEntryPoint.java file should look like this:

view plaincopy to clipboardprint?
  1. package org.yournamehere.client;   
  2.   
  3. import com.google.gwt.http.client.Response;   
  4. import com.google.gwt.http.client.Request;   
  5. import com.google.gwt.http.client.RequestBuilder;   
  6. import com.google.gwt.http.client.RequestCallback;   
  7.   
  8. import com.google.gwt.core.client.EntryPoint;   
  9. import com.google.gwt.core.client.GWT;   
  10. import com.google.gwt.dom.client.Style;   
  11. import com.google.gwt.json.client.*;   
  12.   
  13. import com.google.gwt.user.client.ui.FlowPanel;   
  14. import com.google.gwt.user.client.ui.Hyperlink;   
  15. import com.google.gwt.user.client.ui.RootPanel;   
  16.   
  17. public class MainEntryPoint implements EntryPoint {   
  18.   
  19.     FlowPanel flowPanel = null;   
  20.     int maxFrequency    = 0;   
  21.     int minFrequency    = 600000000;   
  22.   
  23.     final int MIN_FONT_SIZE = 5;   
  24.     final int MAX_FONT_SIZE = 25;   
  25.   
  26.     public void onModuleLoad() {   
  27.   
  28.         getTagData();   
  29.   
  30.         flowPanel = new FlowPanel();   
  31.         flowPanel.setStylePrimaryName("cloudWrap");   
  32.         RootPanel.get("wrapper").add(flowPanel);   
  33.     }   
  34.   
  35.     public void getTagData(){   
  36.   
  37.         String url = "/wmGetTags.php";   
  38.         RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url);   
  39.   
  40.         try{   
  41.             requestBuilder.sendRequest(null, new RequestCallback() {   
  42.   
  43.                 public void onResponseReceived(Request request, Response response) {   
  44.   
  45.                     if (response.getStatusCode() == 200)   
  46.                         handleGetTags(response.getText());   
  47.                 }   
  48.   
  49.                 public void onError(Request request, Throwable exception) {   
  50.                     throw new UnsupportedOperationException("Not supported yet.");   
  51.                 }   
  52.             });   
  53.         } catch (Exception e){   
  54.             e.printStackTrace();   
  55.         }   
  56.     }   
  57.   
  58.   
  59.     public void handleGetTags(String jsonText){   
  60.   
  61.         JSONValue jsonValue = JSONParser.parse(jsonText);   
  62.         JSONArray jsonArray = jsonValue.isArray();   
  63.   
  64.         JSONObject jsonObject;   
  65.         JSONString tagName;   
  66.         JSONNumber tagFreq;   
  67.   
  68.         int frequency;   
  69.   
  70.         if (jsonArray != null){   
  71.   
  72.             for (int i = 0; i < jsonArray.size(); i++){   
  73.   
  74.                 jsonObject = (JSONObject)jsonArray.get(i);   
  75.                 tagFreq = jsonObject.get("frequency").isNumber();   
  76.   
  77.                 frequency = (int)tagFreq.doubleValue();   
  78.   
  79.                 if (minFrequency > frequency)   
  80.                     minFrequency = frequency;   
  81.   
  82.                 if (maxFrequency < frequency)   
  83.                     maxFrequency = frequency;   
  84.             }   
  85.   
  86.             for (int i = 0; i < jsonArray.size(); i++){   
  87.   
  88.                 jsonObject = (JSONObject)jsonArray.get(i);   
  89.   
  90.                 tagName = jsonObject.get("tag"      ).isString();   
  91.                 tagFreq = jsonObject.get("frequency").isNumber();   
  92.   
  93.                 frequency = (int)tagFreq.doubleValue();   
  94.   
  95.                 Hyperlink tagLink = new Hyperlink(tagName.stringValue(),null);   
  96.                 tagLink.setStylePrimaryName("cloudTags");   
  97.   
  98.                 Style linkStyle = tagLink.getElement().getStyle();   
  99.                 linkStyle.setProperty("fontSize",getLabelSize(frequency));   
  100.   
  101.                 flowPanel.add(tagLink);   
  102.             }   
  103.         }   
  104.     }   
  105.   
  106.     public String getLabelSize(int frequency){   
  107.         double weight = (Math.log(frequency) - Math.log(minFrequency)) / (Math.log(maxFrequency) - Math.log(minFrequency));   
  108.         int fontSize = MIN_FONT_SIZE + (int)Math.round((MAX_FONT_SIZE - MIN_FONT_SIZE) * weight);   
  109.         return Integer.toString(fontSize) + "pt";   
  110.     }   
  111. }  
package org.yournamehere.client; import com.google.gwt.http.client.Response; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style; import com.google.gwt.json.client.*; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Hyperlink; import com.google.gwt.user.client.ui.RootPanel; public class MainEntryPoint implements EntryPoint { FlowPanel flowPanel = null; int maxFrequency = 0; int minFrequency = 600000000; final int MIN_FONT_SIZE = 5; final int MAX_FONT_SIZE = 25; public void onModuleLoad() { getTagData(); flowPanel = new FlowPanel(); flowPanel.setStylePrimaryName("cloudWrap"); RootPanel.get("wrapper").add(flowPanel); } public void getTagData(){ String url = "/wmGetTags.php"; RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url); try{ requestBuilder.sendRequest(null, new RequestCallback() { public void onResponseReceived(Request request, Response response) { if (response.getStatusCode() == 200) handleGetTags(response.getText()); } public void onError(Request request, Throwable exception) { throw new UnsupportedOperationException("Not supported yet."); } }); } catch (Exception e){ e.printStackTrace(); } } public void handleGetTags(String jsonText){ JSONValue jsonValue = JSONParser.parse(jsonText); JSONArray jsonArray = jsonValue.isArray(); JSONObject jsonObject; JSONString tagName; JSONNumber tagFreq; int frequency; if (jsonArray != null){ for (int i = 0; i < jsonArray.size(); i++){ jsonObject = (JSONObject)jsonArray.get(i); tagFreq = jsonObject.get("frequency").isNumber(); frequency = (int)tagFreq.doubleValue(); if (minFrequency > frequency) minFrequency = frequency; if (maxFrequency < frequency) maxFrequency = frequency; } for (int i = 0; i < jsonArray.size(); i++){ jsonObject = (JSONObject)jsonArray.get(i); tagName = jsonObject.get("tag" ).isString(); tagFreq = jsonObject.get("frequency").isNumber(); frequency = (int)tagFreq.doubleValue(); Hyperlink tagLink = new Hyperlink(tagName.stringValue(),null); tagLink.setStylePrimaryName("cloudTags"); Style linkStyle = tagLink.getElement().getStyle(); linkStyle.setProperty("fontSize",getLabelSize(frequency)); flowPanel.add(tagLink); } } } public String getLabelSize(int frequency){ double weight = (Math.log(frequency) - Math.log(minFrequency)) / (Math.log(maxFrequency) - Math.log(minFrequency)); int fontSize = MIN_FONT_SIZE + (int)Math.round((MAX_FONT_SIZE - MIN_FONT_SIZE) * weight); return Integer.toString(fontSize) + "pt"; } } 

Summary

This tutorial demonstrated the simple steps required to build a tag-cloud, showing how GWT can connect to a PHP and MySQL back-end to retrieve data. It also showed how to create GWT widgets and stylize them through the familiar CSS techniques. I hope you enjoyed it!

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载