Search code examples
javagwthyperlinkgwt-celltable

GWT : Render a hyperlink in a TextColumn of a CellTable


First of all - I am a beginner with Java and GWT. I have a scripting language background so please be explicit.

I have a CellTable that is populated with data from a database( ServerKeyWord class gets the data ).

    myCellTable.addColumn(new TextColumn<ServerKeyWord>() {

        @Override
        public String getValue(ServerKeyWord object) {
            // TODO Auto-generated method stub
            return object.getName();
        }
    });

The example from above works, but it only shows the data as a text. I need to make it a hyperlink, that when you click it, it opens a new tab to that location. I've surfed the web and got to the conclusion that I need to override render.

public class HyperTextCell extends AbstractCell<ServerKeyWord> {

interface Template extends SafeHtmlTemplates {
    @Template("<a target=\"_blank\" href=\"{0}\">{1}</a>")
    SafeHtml hyperText(SafeUri link, String text);
}

private static Template template;

public static final int LINK_INDEX = 0, URL_INDEX = 1;

/**
 * Construct a new linkCell.
 */
public HyperTextCell() {

    if (template == null) {
        template = GWT.create(Template.class);
    }
}

@Override
public void render(Context context, ServerKeyWord value, SafeHtmlBuilder sb) {
    if (value != null) {

        // The template will sanitize the URI.
        sb.append(template.hyperText(UriUtils.fromString(value.getName()), value.getName()));
        }
    }
}

Now ... How do I use the HyperTextCell class with the addColumn method as in the first code example?!

Thank you in advance!


Solution

  • HyperTextCell hyperTextCell = new HyperTextCell();
        Column<ServerKeyWord, ServerKeyWord> hyperColumn = new Column<ServerKeyWord, ServerKeyWord>(
                hyperTextCell) {
    
            @Override
            public ServerKeyWord getValue(ServerKeyWord keyWord) {
                return keyWord;
            }
        };
        myCellTable.addColumn(hyperColumn);