Sunday, July 25, 2010

How to use CSS and Images with GWT

There are several way to work with CSS in GWT but this is the recommend method.

Set up for Css


1. Create your css file, name it mystyle.css.



Here is a sample content

.prettyText1 {
    color: #454;
}
.prettyText2 {
    text-align: center;
}

2. Create a Java interface for your mystyle.css that extends CssResource.

package com.google.gwt.sample.stockwatcher.client;

import com.google.gwt.resources.client.CssResource;

public interface MyStyle extends CssResource {
    //these names must match the name in mystyle.css
    String prettyText1();
    String prettyText2;
}


3. Create a Java interface that extends the ClientBundle and point it to the mystyle.css location

package com.google.gwt.sample.stockwatcher.client

import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;

public interface MyResources extends ClientBundle {
    public static final MyResources INSTANCE = GWT.create(MyResources.class)

    @Source("css/mystyle.css")
    MyStyle mystyle();
}

Using Css


Make sure the ensureInjected() method is called before referencing the css class.

public class StockWatcher implements EntryPoint {

/**
* This is the entry point method.
*/
public void onModuleLoad() {
    MyResources.INSTANCE.mystyle().ensureInjected();
}


Example of use in UiBinder file.



Example of use in code.

Label lbl = new Label();
lbl.addStyleName(MyResources.INSTANCE.mystyle().prettyText1());


Setting Up Images


1. Put your image in the images folder

2. Add reference to the image in the MyResources interface

package com.google.gwt.sample.stockwatcher.client

import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;

public interface MyResources extends ClientBundle {
    public static final MyResources INSTANCE = GWT.create(MyResources.class)

    @Source("css/mystyle.css")
    MyStyle mystyle();


    @Source("images/20.png")
    ImageResource myImg();
}


Using the image example in code


Image myImage = new Image(MyResources.INSTANCE.myImg());


How to create a css class with back ground image


In your css file, mystyle.css, add the following class

@sprite .bgWithMyImage {
  gwt-image: 'myImg';
}