GWT ramblings of a Flex developer – CSS and Images

Hey!

Last time, we talked about I18N and as promised, this time we’ll discuss CSS handling.

Since you can’t really talk about CSS without talking about images, we’ll also mention them as well.

Well, as seasoned Flex devs, you know that using CSS in Flex is a brease.
You just slap the style tag in your application mxml and you’re done.

In GWT, things are not that easy.

Let’s say you have the css file, say ‘MyCss.css’:

.expanded {
        width: 100%;
	height: 100%;
}

.bold24Title {
	font-size: 24px;
	font-weight: bold;
}

.statusBar {
	font-size: 14px;
}

.mainToolbar {
	padding-left: 10px;
	padding-right: 10px;
}

.loginTitle {
	font-size: 16px;
	font-weight: bold;
}

Now, you want to use it, right?

Well, brace yourself – Yuckiness ahead!

First thing you need to do, is extend CssResource and fill it up with accessors:

public interface MyCss extends CssResource {

	String expanded();

	String bold24Title();

	String statusBar();

	String mainToolbar();

	String loginTitle();
}

Then, you have to extend the ClientBundle imterface:

public interface MyBundle extends ClientBundle {

	@Source("MyCss.css")
	MyCss css();

	@Source("images/image1.png")
	ImageResource image1();

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

* Note: this is also the place where you define image references using ImageResource

   To use it, the CSS should be defined as @sprite and define gwt-image:

@sprite .sampleStyle {
	width: 165px;
	height: 200px;
	margin: 6px;
	background-position: bottom;
	gwt-image: "image1";
}

Then, you have to make sure that MyBundle is injected, in your EntryPoint’s onModuleLoad method:

public void onModuleLoad() {

	// inject css
	MyBundle bundle = GWT.create(MyBundle.class);
	bundle.css().ensureInjected();
}

Now, remember the Services class I mentioned last post?
It comes into play here as well, to facilitate better use of it:

public class Services {
	public static Messages MESSAGES = GWT.create(Messages.class);

	public static MyBundle MY_BUNDLE = GWT.create(MyBundle.class);
	public static MyCss MY_CSS = MY_BUNDLE.css();

}

This is to allow me to use Services.MY_CSS.expanded to get the expanded style from Java code.

When using UiBinder, you’ll have to first define a <ui:with> tag:

<ui:with type="com.examples.resources.MyBundle" field="res"/>

And then use it, for example:

<g:InlineLabel styleName="{res.css.bold24Title}"/>

That’s it for now…

Until next time – Happy coding!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: