GWT CellTable and ListBoxes complex identifiers - gwt

I'm following Goolge's example on how to add ListBoxes/SelectionCells to a CellTable, but I can't figure how to change the behaviour so the matching is done not with the string value displayed.
The items I display #SelectionCell are not unique (i.e there can be 2 elements with the same name), so I need to use other fields associated with the object to know which one was selected
for (IrrigationProgramDTO program: programOptions)
categoryNames.add(program.getName());
SelectionCell categoryCell = new SelectionCell(categoryNames);
Column<IrrigationGapDTO, String> categoryColumn = new Column<IrrigationGapDTO, String> (categoryCell) {
#Override
public String getValue(IrrigationGapDTO object) {
if (object.getProgramSelected()!=null)
return object.getProgramSelected().getName();
else
return "";
}
};
categoryColumn.setFieldUpdater(new FieldUpdater<IrrigationGapDTO, String>() {
public void update(int index, IrrigationGapDTO object, String value) {
for (IrrigationProgramDTO program: programOptions) {
//not valid as there could be more than 1 program with the same name
if (program.getName().equals(value)) {
object.setProgramSelected(program);
break;
}
}
}

Here is my new implementation of solution #3 (note that you must add a FieldUpdater to the column for it to work):
import java.util.Arrays;
import java.util.List;
import com.google.gwt.cell.client.AbstractEditableCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.BrowserEvents;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.SelectElement;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.client.SafeHtmlTemplates.Template;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
/**
* A {#link Cell} used to render a drop-down list.
*
* #author Gaspard van Koningsveld
*/
public class ItemSelectionCell<C> extends AbstractEditableCell<C, C> {
interface Template extends SafeHtmlTemplates {
#Template("<select tabindex=\"-1\" style=\"width:100%\">")
SafeHtml beginSelect();
#Template("<option value=\"{0}\">{1}</option>")
SafeHtml deselected(int hash, String option);
#Template("<option value=\"{0}\" selected=\"selected\">{1}</option>")
SafeHtml selected(int hash, String option);
#Template("</select>")
SafeHtml endSelect();
}
private static Template template;
private List<C> items;
public ItemSelectionCell(C itemsArray[]) {
this(Arrays.asList(itemsArray));
}
public ItemSelectionCell(List<C> items) {
super(BrowserEvents.CHANGE);
if (template == null) {
template = GWT.create(Template.class);
}
this.items = items;
}
#Override
public void onBrowserEvent(Context context, Element parent, C value, NativeEvent event, ValueUpdater<C> valueUpdater) {
super.onBrowserEvent(context, parent, value, event, valueUpdater);
if (BrowserEvents.CHANGE.equals(event.getType())) {
SelectElement select = parent.getFirstChild().cast();
int newIndex = select.getSelectedIndex();
valueUpdater.update(items.get(newIndex));
}
}
#Override
public void render(Context context, C value, SafeHtmlBuilder sb) {
sb.append(template.beginSelect());
for (int i = 0; i < items.size(); i++) {
C item = items.get(i);
if (item.equals(value)) {
sb.append(template.selected(i, getItemDisplayString(item)));
} else {
sb.append(template.deselected(i, getItemDisplayString(item)));
}
}
sb.append(template.endSelect());
}
public String getItemDisplayString(C item) {
return item.toString();
}
public List<C> getItems() {
return items;
}
public void setItems(List<C> items) {
this.items = items;
}
#Override
public boolean isEditing(Context context, Element parent, C value) {
return false;
}
}

3 possible solutions:
1. Dirty workaround:
Instead of getName() return getName() + some unique identifier:
public String getValue(IrrigationGapDTO object) {
if (object.getProgramSelected()!=null)
return object.getProgramSelected().getName()+"_"+object.getUniqueIdentiufier();
else
return "";
}
then in the FieldUpdater you can split on the "_" character and deal with duplicates
2. Use a unique id instead of getName():
Just generate/assign a unique id to your programms and use it instead of name.
3. Use IrrigationProgramDTO type instead of String:
Instead of String you can use IrrigationProgramDTO class in the Column definition. However you probably have to use a user-defined SelectionCell which takes IrrigationProgramDTO type instead of String as Data-type.
Column<IrrigationGapDTO, IrrigationProgramDTO> categoryColumn = new Column<IrrigationGapDTO, IrrigationProgramDTO> (categoryCell) {
#Override
public IrrigationProgramDTO (IrrigationGapDTO object) {
if (object.getProgramSelected()!=null)
return object.getProgramSelected();
else
return null;
}
};
categoryColumn.setFieldUpdater(new FieldUpdater<IrrigationGapDTO, IrrigationProgramDTO>() {
public void update(int index, IrrigationGapDTO object, IrrigationProgramDTO value) {
object.setProgramSelected(program);
}
}

Here is my implementation of Solution #3 of #Ümit:
public static abstract class EditSelectColumn<E, S> {
Map<String, S> selectionMap = new HashMap<String, S>();
EditColumn<E> column;
protected final String relationshipFieldName;
public EditSelectColumn(String relationshipFieldName) {
this.relationshipFieldName = relationshipFieldName;
for (S option : getOptions()) {
assert getOptionString(option) != null : "Option string cannot be null, please check your database";
selectionMap.put(getOptionString(option), option);
}
SelectionCell cell = new SelectionCell(new ArrayList<String>(selectionMap.keySet()));
column = new EditColumn<E>(cell) {
#Override
public String getValue(E object) {
if (getOption(object) == null)
return "";
return getOptionString(getOption(object));
}
#Override
public void setValue(E object, String value) {
setOption(object, selectionMap.get(value));
}
};
}
public EditColumn<E> getColumn() {
return column;
}
public abstract List<S> getOptions();
public abstract String getOptionString(S option);
public abstract S getOption(E object);
public abstract void setOption(E object, S value);
}

Related

GWT celltable. How to set cell css style after changing value in EditTextCell

Base on user's entry in editable cell I would like to display concrete style. What I am trying to do is a very base validation.
I've tried already override getCellStyleNames in Anonymous new Column() {}, but this work on start, base on model values, but what would work, after user change value of that cell?
Please help.
You're very close.
Override getCellStyleNames in the new Column() {} is the first half of the solution.
The second half:
yourColumn.setFieldUpdater(new FieldUpdater<DataType, String>() {
#Override
public void update(int index, DataType object, String value) {
// the following line will apply the correct css
// based on the current cell value
cellTable.redrawRow(index);
}
});
Hope this would help!
The following code is a trivia but complete example.
A celltable with two column is defined. Each cell in the first column displays a simple question. Each cell in the second column is an editable cell which allows you to enter you answer to the question shown in first column. If your answer is correct, then the text of the answer will be styled as bold and black. Otherwise, the text will be styled as red in normal font weight.
Source code of the trivia GWT app:
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.RootPanel;
import java.util.Arrays;
import java.util.List;
public class CellTableExample implements EntryPoint {
private static class Question {
private final String question;
private final String correctAnswer;
private String userProvidedAnswer;
public Question(String question, String correctAnswer) {
this.question = question;
this.correctAnswer = correctAnswer;
this.userProvidedAnswer = "";
}
public String getQuestion() {
return question;
}
public String getCorrectAnswer() {
return correctAnswer;
}
public String getUserProvidedAnswer() {
return userProvidedAnswer;
}
public void setUserProvidedAnswer(String userProvidedAnswer) {
this.userProvidedAnswer = userProvidedAnswer;
}
}
private static final List<Question> questionList = Arrays.asList(
new Question("Which city is capital of England?", "London"),
new Question("Which city is capital of Japan?", "Tokyo"));
#Override
public void onModuleLoad() {
final CellTable<Question> cellTable = new CellTable<>();
TextColumn<Question> questionCol = new TextColumn<Question>() {
#Override
public String getValue(Question object) {
return object.getQuestion();
}
};
Column<Question, String> ansCol = new Column<Question, String>(new EditTextCell()) {
#Override
public String getValue(Question object) {
return object.getUserProvidedAnswer();
}
#Override
public String getCellStyleNames(Cell.Context context, Question object) {
if (object.getUserProvidedAnswer().equalsIgnoreCase(object.getCorrectAnswer())) {
return "correct-answer";
} else {
return "wrong-answer";
}
}
};
ansCol.setFieldUpdater(new FieldUpdater<Question, String>() {
#Override
public void update(int index, Question object, String value) {
object.setUserProvidedAnswer(value);
cellTable.redrawRow(index);
}
});
cellTable.addColumn(questionCol, "Question");
cellTable.addColumn(ansCol, "Your Answer");
cellTable.setRowData(0, questionList);
RootPanel.get().add(cellTable);
}
}
Companion css file:
.correct-answer {
font-weight: bold;
color: black;
}
.wrong-answer {
font-weight: normal;
color: red;
}
Screenshot1: Right after the app started. The column of answers was empty.
Screenshot2: After I entered answers. Apparently I answered the first one correctly but not the second one.
Use setCellStyleNames inside the render method:
Column<MyType, String> testColumn = new Column<MyType, String>(new EditTextCell()) {
#Override
public String getValue(MyType object) {
return object.getValue();
}
#Override
public void render(Context context, MyType object, SafeHtmlBuilder sb) {
if(object.isValid())
setCellStyleNames("validStyleNames");
else
setCellStyleNames("invalidStyleNames");
super.render(context, object, sb);
}
};
Correct aproach is to overide getCellStyleNames method in anonymous class:
new Column<Model, String>(new EditTextCell())
You have to return string name of css class.

TreeTableView disable any cell in parent row

How can I disable any cell editable in parent row in treetableview? Please look the pictures and check the sample code. Shortly I want to disable row editable if row is expandable (root row or sub root row)
this picture is correct
but this is not correct
**Example code **
import javafx.application.Application;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.scene.control.cell.TreeItemPropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Callback;
public class TreeTableExample extends Application {
public static void main(String[] args) {
Application.launch(args);
}
#Override
#SuppressWarnings("unchecked")
public void start(Stage stage) {
HBox root = new HBox(createTable());
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Using a TreeTableView");
stage.show();
}
public TreeTableView createTable() {
TreeTableView<Person> treeTable = new TreeTableView<>();
treeTable.setEditable(true);
Callback<TreeTableColumn<Person, String>,
TreeTableCell<Person, String>> cellFactory
= (TreeTableColumn<Person, String> p) -> new EditingCell();
TreeTableColumn<Person, String> firstName = new TreeTableColumn<>("First Name");
firstName.setCellValueFactory(new TreeItemPropertyValueFactory<>("firstName"));
firstName.setCellFactory(cellFactory);
firstName.setOnEditCommit((TreeTableColumn.CellEditEvent<Person, String> event) -> {
if(event.getNewValue()!=null)
event.getRowValue().getValue().setFirstName(event.getNewValue());
});
TreeTableColumn<Person, String> lastName = new TreeTableColumn<>("Last Name");
lastName.setCellValueFactory(new TreeItemPropertyValueFactory<>("lastName"));
lastName.setCellFactory(cellFactory);
lastName.setOnEditCommit((TreeTableColumn.CellEditEvent<Person, String> event) -> {
if(event.getNewValue()!=null)
event.getRowValue().getValue().setLastName(event.getNewValue());
});
treeTable.getColumns().addAll(firstName, lastName);
TreeItem<Person> root = new TreeItem<>();
for (int i = 0; i < 5; i++) {
root.getChildren().add(new TreeItem<>(new Person()));
}
treeTable.setRoot(root);
return treeTable;
}
public class Person {
private SimpleStringProperty firstName;
private SimpleStringProperty lastName;
public Person(){
firstName = new SimpleStringProperty(this, "firstName");
lastName = new SimpleStringProperty(this, "lastName");
};
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String fName) {
lastName.set(fName);
}
}
class EditingCell extends TreeTableCell<Person, String> {
private TextField textField;
public EditingCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else if (isEditing()) {
if(!getTreeTableView().getTreeItem(getIndex()).isLeaf())
setEditable(false);
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
textField.focusedProperty().addListener(
(ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) -> {
if (!arg2) {
commitEdit(textField.getText());
}
});
}
private String getString() {
return getItem() == null ? "" : getItem();
}
}
}
just run it and double click on the root item
make-individual-cell-editable-in-javafx-tableview I checked the solution works for tableview but for treetaleview does not work.
It seems that TreeTableCell does not properly check its editable property before deciding whether or not to call startEdit(). I think that's a bug. You can work around it by checking that yourself in your startEdit() method:
#Override
public void startEdit() {
if (isEditable() && !isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
and now in your updateItem() method, you can check the current tree item from the row, and update editable as required:
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
TreeItem<Person> treeItem = getTreeTableRow().getTreeItem();
setEditable(treeItem != null && treeItem.isLeaf());
if (empty) {
setText(null);
setGraphic(null);
} else if (isEditing()) {
if(!getTreeTableView().getTreeItem(getIndex()).isLeaf())
setEditable(false);
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
Actually I disagree with the reasoning in the other answer: there is nothing wrong with core TreeTableCell (it does check for its editability before actually starting an edit) - instead the logic in the custom cell implementation is broken. Particularly, the part of updateItem that sets the editable property:
} else if (isEditing()) {
if(!getTreeTableView().getTreeItem(getIndex()).isLeaf())
setEditable(false);
Besides being incomplete in not resetting the editable back to true anywhere (remember: cells are re-used), we allow super to first start editing and only after it started, it's disabled.
This logic error is fixed (in the other answer, copied here for convenience) by unconditionally setting the editability in updateItem:
super.updateItem(item, empty);
TreeItem<Person> treeItem = getTreeTableRow().getTreeItem();
setEditable(treeItem != null && treeItem.isLeaf());
The other usage error (as already noted) was not fully checking cell state before actually configuring the editor. The suggested fix - check cell's editable - isn't quite complete because table/column editability might be disabled as well. To take that into account, I would tend to let super do its job and only configure the editor if editability actually changed, like
super.startEdit();
// super changed state into editing
if (isEditing()) {
// create and install the textField
}

GXT 3.x RowExpander with ButtonCell

I try to add button into rowExpander content:
so i have:
ButtonCell<Integer> viewButtonCell = new ButtonCell<Integer>();
and row expander
RowExpander<XX> expander = new RowExpander<XX>(identity, new AbstractCell<XX>() {
#Override
public void render(Context context, XX value, SafeHtmlBuilder sb) {
sb.appendHtmlConstant("<span>");
viewButtonCell.render(context, value.getId(), sb);
sb.appendHtmlConstant("</span>");
}
ButtonCell is rendered OK i can see it BUT I cannot click it, no selecthandler from ButtonCell is call :(.
Any ideas how can I make selectHandlerActive for this button ?
Thanks
i created some new RowExpander :
public class MTPRowExpander<M> extends RowExpander<M> {
public static int id = 0;
public static interface WidgetFactory<M> {
public Widget createWidget(M model);
}
private WidgetFactory<M> wf;
private Set<Integer> expandedRows;
public MTPRowExpander(IdentityValueProvider<M> valueProvider,WidgetFactory<M> wf) {
this(valueProvider,GWT.<RowExpanderAppearance<M>> create(RowExpanderAppearance.class),wf);
}
public MTPRowExpander(IdentityValueProvider<M> valueProvider,final RowExpanderAppearance<M> appearance, WidgetFactory<M> wf) {
super(valueProvider, null, appearance);
this.wf = wf;
expandedRows = new HashSet<Integer>();
}
#Override
protected boolean beforeExpand(M model, Element body, XElement row,int rowIndex) {
if (expandedRows.contains(rowIndex)) {
return true;
} else {
expandedRows.add(rowIndex);
return super.beforeExpand(model, body, row, rowIndex);
}
}
#Override
protected String getBodyContent(final M model, int rowIndex) {
final int curentid = id++;
Scheduler.get().scheduleFinally(new ScheduledCommand() {
#Override
public void execute() {
Widget widget = wf.createWidget(model);
com.google.gwt.dom.client.Element item = grid.getElement().childElement(".widget" + curentid);
item.appendChild(widget.getElement());
ComponentHelper.setParent(grid, widget);
}
});
return "<div class='widget" + curentid + "'></div>";
}
}
I know that this solution is not perfect but I didnt know how to resolve problem at more proper way.

GWT ImageCell: Change image dynamically in a DataGrid or CellTable

I have DataGrid where one on of the columns contains images. I used this code to generate the column.
Column<Job, String> expandHideColumn = new Column<Job, String>(
imageCell) {
#Override
public String getValue(Job object) {
return null;
}
#Override
public void render(Context context, Job Object, SafeHtmlBuilder sb) {
sb.appendHtmlConstant("<img src='images/expand.jpeg' style='cursor: pointer' />");
}
}
What I want is on clicking the image it has to change. For this I added a click handler on the ImageCell like this
ImageCell imageCell = new ImageCell() {
#Override
public Set<String> getConsumedEvents() {
Set<String> events = new HashSet<String>();
events.add("click");
return events;
}
};
In the onBrowserEvent method I wrote this
#Override
public void onBrowserEvent(Context context, Element element,
Job job, NativeEvent event) {
if (element.getFirstChildElement().isOrHasChild(
Element.as(event.getEventTarget()))) {
if (element.getFirstChildElement().getPropertyString("src")
.matches("(.*)expand.jpeg")) {
element.getFirstChildElement().setPropertyString("src",
"images/collapse.jpeg");
} else {
element.getFirstChildElement().setPropertyString("src",
"images/expand.jpeg");
}
}
}
I don't think this is a good approach to change images on click event. Is there a better solution?
You can use a column value for know the state of the column :
Column<Job, Boolean> expandHideColumn = new Column<Job, Boolean>(new ImageExpandCollapseCell()) {
#Override
public Boolean getValue(Job object) {
return object.isExpand(); //The object know the expand state ?
}
}
expandHideColumn.setValueUpdater(new FieldUpdater<Job, Boolean>() {
void update(int index, Job object, Boolean value) {
object.setExpand(value);
}
});
The ImageExpandCollapseCell look like this :
public class ImageExpandCollapseCell extends AbstractCell<Boolean> {
final String EXPAND = "images/expand.jpeg";
final String COLLAPSE = "images/collapse.jpeg";
interface Template extends SafeHtmlTemplates {
#Template("<div style=\"float:right\"><img src=\"" + url + "\"></div>")
SafeHtml img(String url);
}
private static Template template;
/**
* Construct a new ImageCell.
*/
public ImageCell() {
super("click"); //Replace your getConsumedEvents()
if (template == null) {
template = GWT.create(Template.class);
}
}
#Override
public void render(Context context, Boolean value, SafeHtmlBuilder sb) {
if (value != null) {
sb.append(template.img(UriUtils.fromSafeConstant(value ? EXPAND : COLLAPSE)));
}
}
#Override
public void onBrowserEvent(Context context, Element element,
Boolean value, NativeEvent event, ValueUpdater<Boolean> valueUpdater) {
valueUpdate.update(!value);
}
}
I improve the proposed version of user905374
It's not a good idea to instantiate new value in the render method.
The column render method call the Cell render method, you musn't replace it !
With the FieldUpdater, you can change the state of the image : expand or collapse and update the cell display (it will be rendered again).

How to add clickhandler on ImageCell in GWT CellTable?

I have tried this but didn't work
Column<ContactInfo, String> imageColumn = new Column<ContactInfo, String>(new ImageCell()) {
#Override
public String getValue(ContactInfo object) {
return "contact.jpg";
}
};
imageColumn.setFieldUpdater(new FieldUpdater<ContactInfo, String>() {
#Override
public void update(int index, ContactInfo object, String value) {
Window.alert("You clicked " + object.firstName);
}
});
cellTable.addColumn(imageColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
public class ButtonImageCell extends ButtonCell{
#Override
public void render(com.google.gwt.cell.client.Cell.Context context,
String value, SafeHtmlBuilder sb) {
SafeHtml html = SafeHtmlUtils.fromTrustedString(new Image(value).toString());
sb.append(html);
}
}
in use:
final Column<ReportDTOProxy, String> buttonImageCellTest = new Column<ProxyObject, String>(new ButtonImageCell()) {
#Override
public String getValue(ProxyObject row) {
//url to image
return row.getImageUrl();
}
};
You can extend ImageCell class and override 2 it's methods - getConsumedEvents and onBrowserEvent. Example:
private class MyImageCell extends ImageCell{
#Override
public Set<String> getConsumedEvents() {
Set<String> consumedEvents = new HashSet<String>();
consumedEvents.add("dblclick");
return consumedEvents;
}
#Override
public void onBrowserEvent(Context context, Element parent,
String value, NativeEvent event,
ValueUpdater<String> valueUpdater) {
switch (DOM.eventGetType((Event)event)) {
case Event.ONDBLCLICK:
// TODO
break;
default:
break;
}
}
}
I did something similar mixing a Button cell with the renderer from an ImageCell....
ButtonCell bc = new ButtonCell() {
#Override
public void render(Context context, SafeHtml data, SafeHtmlBuilder sb) {
if (data != null) {
ImageResource icon = Icons.BUNDLE.pieChart();
SafeHtml html = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(icon).getHTML());
sb.append(html);
}
}
};
You get the idea. The only problem is that it does not display the "hand" icon when you hover over it.... likely it can be fixed by setting the CSS.
You can try this rather than using ButtonCell or ImageCell. This will work for sure. As I have implemented for my requirement. Let me know how does it goes..
ClickableTextCell imageCell = new ClickableTextCell() {
#Override
public void render(Context context, SafeHtml data, SafeHtmlBuilder sb) {
if (data != null) {
String imagePath = "icon.png";
sb.append(imagePath);
}
}
};
Column<ContactInfo, String> imageColumn = new Column<ContactInfo, String>(imageCell) {
#Override
public String getValue(ContactInfo object) {
return "";
}
};
imageColumn.setFieldUpdater(new FieldUpdater<ContactInfo, String>() {
#Override
public void update(int index, ContactInfo object, String value) {
Window.alert("You clicked " + object.firstName);
}
});
cellTable.addColumn(imageColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
A good solution for this issue, if you use ActionCell that is able to handle clicking. The use of it is a bit complicatied, but for me it worked pretty well.
First you need to initialize ActionCell with a delegate, in the constructor, write new ActionCell.Delegate<your class>. In this override the method execute and in that write your code that handle the clicking event.
The other thing you need to do is building up a html from the image. The SafeHtmlUtils class gives you a very easy way to do that. It's fromTrustedString method helps you building up the html:
SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create ("Your image from a resource class").getHTML());
This way the SafeHtml field can be initalized and if you give the ActionCell's contructor the SafeHtml and the Delegate, that it will do the work for you.
In this example a button will be initialized with the image from the bundle file in it. You can make it without the button if you override the render method of the ActionCell and append the SafeHtmlBuilder in the method with the same SafeHtml variable as above.
My code looks like the following:
IdentityColumn<Type> imageCell = new IdentityColumn<Type>(new ActionCell<Type>("AnyString",
new ActionCell.Delegate<Type>() {
#Override
public void execute(final Type item) {
"your code"
}
}) {
#Override
public void render(Context context, Type value, SafeHtmlBuilder sb) {
if (value != null) {
SafeHtml html = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(resource.image).getHTML());
sb.append(html);
}
}
});
You'd rather override the method in an another class but I didn't want to split them for this post. It worked for me very well, I hope it will help other's too.
I got all the above and added them in my app. Thanks to all. stackoverflow rocks!
ButtonCell bc = new ButtonCell() {
#Override
public void render(Context context, SafeHtml data, SafeHtmlBuilder sb) {
if (data != null) {
ImageResource icon = Connector.imageResources.minus();
Image image = new Image(icon);
//fix the mouse pointer
image.getElement().getStyle().setCursor(Cursor.POINTER);
//Do something with the DATA
image.setTitle("Delete " + data.asString());
SafeHtml html = SafeHtmlUtils.fromTrustedString(image.toString());
sb.append(html);
}
}
};
Column<InstanceProperty, String> imageColumn = new Column<InstanceProperty, String>(bc) {
#Override
public String getValue(InstanceProperty object) {
//return the DATA
return object.getKey();
}
};
imageColumn.setFieldUpdater(new FieldUpdater<InstanceProperty, String>() {
#Override
public void update(int index, InstanceProperty property,
String value) {
//you can also use the DATA to do something
InstancePropertiesTable.this.dataProvider.getList().remove(index);
}
});
addColumn(imageColumn, "");
This worked for me:
public class ButtonImageCell extends ButtonCell{
#Override
public void render(com.google.gwt.cell.client.Cell.Context context,
String renderedHtmlStr, SafeHtmlBuilder sb) {
sb.appendHtmlConstant(renderedHtmlStr);
}
}
In a class containing CellTable table:
TableResources resources = GWT.create(TableResources.class);
ImageResourceRenderer imageRenderer = new ImageResourceRenderer();
...
Column<MyRecord, String> buttonCol = new Column<MyRecord, String>(new ButtonImageCell()) {
#Override
public String getValue(MyRecord record) {
if(record.isOn())
return imageRenderer.render(resources.getOnImg()).asString();
else
return imageRenderer.render(resources.getOffImg()).asString();
}
};
buttonCol.setFieldUpdater(new FieldUpdater<MyRecord, String>() {
public void update(int index, MyRecordobject, String value) {
if (Window.confirm("Do stuff?")) {
//todo: stuff
}
}
});
...
table.addColumn(buttonCol, "");
Where the ImageResource comes from (resources):
public interface TableResources extends CellTable.Resources {
interface TableStyle extends CellTable.Style {
}
#Source("/images/on.png")
ImageResource getOnImg();
#Source("/images/off.png")
ImageResource getOffImg();
}
You need to sinkEvents() with appropriate bits.
Refer to answer of Question Adding ClickHandler to div which contains many other widget.