GWT中自定义你的"cell"

  GWT内部提供了CellTable组件,它允许自由增加column以及cell,在设定column之后就是在其中填充cell了。但GWT所提供的CellTable样式确实不敢恭维,为了解决这一问题,在网上找了一些可行的方法,结合我的实践,在此贴出代码及说明,以供参考。

  创建column代码:

protected Column<Item, String> createNameColumn(CellTable<Item> parent) {

    Column<Item,String> column = new Column<Item,String>(new MytextCell()) {

        public String getCellStyleNames(Context context,
        EntityItem<Product> object) {
                return "label_link_focus_style";
        }

            public String getValue(item) {
            //code here                    
        }
};

上面的代码中,我使用的是一个MyTextCell,一个我自定义的textCell,它继承于TextCell,所以重写了textCell中的getCellStyleNames()方法,只需要要返回一个css中的class名称字符串即可。这样做可以改变该cell的样式,但有一个缺点,不够灵活,仅仅改变cell样式,cell里面的内容不能改变。比如我想给cell中的字体加个下划线或者改个颜色,这种方法就不能完全实现。

 看看MytextCell类的代码:

 1 public class MyTextCell extends TextCell {
 2   
 3       private static Template template;
 4       
 5      interface Template extends SafeHtmlTemplates {
 6          @Template("<div style="color:{0};text-decoration:{1}">{2}</div>")
 7          SafeHtml div(String url, String decoration, String value);
 8      }
 9  
10      @Override
11      public void render(com.google.gwt.cell.client.Cell.Context context, String value, SafeHtmlBuilder sb) {
12         String color = "#0066DD";
13          String decoration = "underline";
14          if (value != null) {
15              sb.append(template.div(color, decoration, value));
16          }
17      }
18 }

在该类中,我重写了TextCell中的render()方法,通过该方法,给cell中的内容添加样式。首先定义一个静态的Template接口,我称它为模板,这个Template继承与SaftHtmlTemplates。然后在其接口中通过注解定义模板样式以及调用格式,如6、7行所示写法。其中的模板中存在{0}、{1}这样的形式,有些类似于一种占位符

接着在render()方法中调用刚才定义的接口,并将占位符填上你希望实现的css样式即可。这样就能轻松更改cell里面的内容的样式了!

原文地址:https://www.cnblogs.com/bigbang92/p/GWTcell-changeStyle.html