Sneaking Custom CSS into a GXT Grid

Jul 3, 2014   #gxt  #ui  #java 

Every time I try to add some custom CSS to a Sencha GXT 3 Grid I have to look up the details again because of the relatively large amount of unintuitive code that is necessary for that simple task.

So I decided to write a short wrap-up of the process as a reference.

First create a file in the client classpath with your custom CSS in it.

.cellDisabled { background-color: #EEEEEE !important; color: #000000; }

Next, create a custom MyGridAppearance that extends the GridAppearance your application is using (e.g. GrayGridAppearance).

public class MyGridAppearance extends GrayGridAppearance { }

In this Appearance include an interface that extends the style of the component you want to add your custom style to. The interface must include a method named after your custom CSS style.

public class MyGridAppearance extends GrayGridAppearance { public interface MyGridStyle extends GrayGridStyle { String cellDisabled(); } }

Now include another interface that pulls your CSS file into the bundle. It must have a @Source annotation with all the CSS files along the inheritance path and your custom CSS file as well.

public class MyGridAppearance extends GrayGridAppearance { public interface MyGridStyle extends GrayGridStyle { String cellDisabled(); } public interface MyGridResources extends GrayGridResources, ClientBundle { @Override @Source({ "com/sencha/gxt/theme/base/client/grid/Grid.css", "com/sencha/gxt/theme/gray/client/grid/GrayGrid.css", "com/codebrickie/sample/client/css/MyGrid.css" }) MyGridStyle css(); } }

The last step for the Appearance is to implement two constructors.

public class MyGridAppearance extends GrayGridAppearance { public interface MyGridStyle extends GrayGridStyle { String cellDisabled(); } public interface MyGridResources extends GrayGridResources, ClientBundle { @Override @Source({ "com/sencha/gxt/theme/base/client/grid/Grid.css", "com/sencha/gxt/theme/gray/client/grid/GrayGrid.css", "com/codebrickie/sample/client/css/MyGrid.css" }) MyGridStyle css(); } public MyGridAppearance() { this(GWT. create(MyGridResources.class)); } public MyGridAppearance(final MyGridResources resources) { super(resources); } }

Now that the Appearance is finished, you have to set it to your grid upon creation.

//... grid = new Grid(store, columnModel, new GridView( new MyGridAppearance())); //... }

Afterwards you can use your custom style e.g. in getColStyle().

//... GridViewConfig viewConfig = new GridViewConfig() { final MyGridStyle styles = (MyGridStyle) ((MyGridAppearance) grid .getView().getAppearance()) .styles(); @Override public String getColStyle(final MyModel model, final ValueProvider valueProvider, final int rowIndex, final int colIndex) { String style = null; if (!model.isEnabled()) { style = styles.cellDisabled(); } return style; } @Override public String getRowStyle(final MyModel model, final int rowIndex) { return null; } }; //...