Building a custom row on demand with GWT CellTableBuilder - gwt

In GWT 2.5 RC CellTableBuilder API was introduced but there are no comprehensive documentation available yet. Is there any tutorial\example of implementing on-demand custom row building with CellTableBuilder? The only example I've found so far was this one http://showcase2.jlabanca-testing.appspot.com/#!CwCustomDataGrid but it is quite confusing for me.
So, my goal is to create extra row containing widget that provides details about clicked row in a table.

I've found suitable solution for this problem. Here is the code sample:
public class CustomCellTableBuilder extends AbstractCellTableBuilder<Object>{
//here go fields, ctor etc.
//ids of elements which details we are going to show
private Set elements;
#Override
protected void buildRowImpl(Object rowValue, int absRowIndex){
//building main rows logic
if(elements.contains(absRowIndex)){
buildExtraRow(absRowIndex, rowValue);
elements.add(absRowIndex);
}
}
private void buildExtraRow(int index, Object rowValue){
TableRowBuilder row = startRow();
TableCellBuilder td = row.startTD().colSpan(getColumns().size());
DivBuilder div = td.startDiv();
Widget widget = new Widget();
//update widget state and appearance here depending on rowValue
div.html(SafeHtmlUtils.fromTrustedString(widget.getElement().getInnerHTML()));
div.end();
td.endTD();
row.endTR();
}}
It should be mentioned, that when you handle some event which leads to appearance of extra row, you should invoke redrawRaw(rowIndex) on CellTable which is attached to TableBuilder. And before this call it is necessary to add target row ID to elements Set.
Hope this was helpful.

I have created this class for expanding rows in GWT. It takes a column that you want to expand and replaces it with a place holder that can have 2 states.
I use it like this:
PlaceHolderColumn<Notification, SafeHtml> placeholder = new PlaceHolderColumn<Notification, SafeHtml>(new SafeHtmlCell()) {
#Override
public SafeHtml getValue(Notification object) {
return SafeHtmlUtils.fromSafeConstant(getSelected() ? "<i class=\"glyphicon glyphicon-chevron-down\"></i>"
: "<i class=\"glyphicon glyphicon-chevron-right\"></i>");
}
};
notificationsTable.setTableBuilder(new ExpandableCellTableBuilder<Notification, SafeHtml>(notificationsTable, columnBody, placeholder));
I have access to glyphicon so I use those instead of the default placeholder column which is +/-
< Image here... but for lack of reputation :( >
columnBody in the above code sample is just a standard column that will span the width of the table. The place holder will be displayed in its place in whatever position columnBody was configured to sit at.
Hope that helps someone :)
public class ExpandableCellTableBuilder<T, U> extends AbstractCellTableBuilder<T> {
private Column<T, U> expandColumn = null;
private PlaceHolderColumn<T, ?> placeholderColumn = null;
private final String evenRowStyle;
private final String oddRowStyle;
private final String selectedRowStyle;
private final String cellStyle;
private final String evenCellStyle;
private final String oddCellStyle;
private final String firstColumnStyle;
private final String lastColumnStyle;
private final String selectedCellStyle;
public static class ExpandMultiSelectionModel<T> extends AbstractSelectionModel<T> {
Map<Object, T> selected = new HashMap<Object, T>();
/**
* #param keyProvider
*/
public ExpandMultiSelectionModel(ProvidesKey<T> keyProvider) {
super(keyProvider);
}
/*
* (non-Javadoc)
*
* #see com.google.gwt.view.client.SelectionModel#isSelected(java.lang.Object)
*/
#Override
public boolean isSelected(T object) {
return isKeySelected(getKey(object));
}
protected boolean isKeySelected(Object key) {
return selected.get(key) != null;
}
/*
* (non-Javadoc)
*
* #see com.google.gwt.view.client.SelectionModel#setSelected(java.lang.Object, boolean)
*/
#Override
public void setSelected(T object, boolean selected) {
Object key = getKey(object);
if (isKeySelected(key)) {
this.selected.remove(key);
} else {
this.selected.put(key, object);
}
scheduleSelectionChangeEvent();
}
}
public static abstract class PlaceHolderColumn<T, C> extends Column<T, C> {
private boolean isSelected;
/**
* #param cell
*/
public PlaceHolderColumn(Cell<C> cell) {
super(cell);
}
protected boolean getSelected() {
return isSelected;
}
}
private int expandColumnIndex;
public ExpandableCellTableBuilder(AbstractCellTable<T> cellTable, Column<T, U> expandColumn) {
this(cellTable, expandColumn, new ExpandMultiSelectionModel<T>(cellTable.getKeyProvider()), null);
}
public ExpandableCellTableBuilder(AbstractCellTable<T> cellTable, Column<T, U> exandColumn, SelectionModel<T> selectionModel) {
this(cellTable, exandColumn, selectionModel, null);
}
public ExpandableCellTableBuilder(AbstractCellTable<T> cellTable, Column<T, U> exandColumn, PlaceHolderColumn<T, ?> placeHolder) {
this(cellTable, exandColumn, new ExpandMultiSelectionModel<T>(cellTable.getKeyProvider()), placeHolder);
}
/**
* #param cellTable
* #param columnBody
*/
public ExpandableCellTableBuilder(AbstractCellTable<T> cellTable, Column<T, U> expandColumn, SelectionModel<T> selectionModel,
PlaceHolderColumn<T, ?> placeHolder) {
super(cellTable);
this.expandColumn = expandColumn;
this.cellTable.setSelectionModel(selectionModel);
if (placeHolder == null) {
this.placeholderColumn = new PlaceHolderColumn<T, String>(new TextCell()) {
#Override
public String getValue(T object) {
return getSelected() ? "-" : "+";
}
};
} else {
this.placeholderColumn = placeHolder;
}
// Cache styles for faster access.
Style style = cellTable.getResources().style();
evenRowStyle = style.evenRow();
oddRowStyle = style.oddRow();
selectedRowStyle = " " + style.selectedRow();
cellStyle = style.cell();
evenCellStyle = " " + style.evenRowCell();
oddCellStyle = " " + style.oddRowCell();
firstColumnStyle = " " + style.firstColumn();
lastColumnStyle = " " + style.lastColumn();
selectedCellStyle = " " + style.selectedRowCell();
}
/*
* (non-Javadoc)
*
* #see com.google.gwt.user.cellview.client.AbstractCellTableBuilder#buildRowImpl(java.lang.Object, int)
*/
#Override
protected void buildRowImpl(T rowValue, int absRowIndex) {
// Calculate the row styles.
SelectionModel<? super T> selectionModel = cellTable.getSelectionModel();
final boolean isSelected = (selectionModel == null || rowValue == null) ? false : selectionModel.isSelected(rowValue);
boolean isEven = absRowIndex % 2 == 0;
StringBuilder trClasses = new StringBuilder(isEven ? evenRowStyle : oddRowStyle);
if (isSelected) {
trClasses.append(selectedRowStyle);
}
// Add custom row styles.
RowStyles<T> rowStyles = cellTable.getRowStyles();
if (rowStyles != null) {
String extraRowStyles = rowStyles.getStyleNames(rowValue, absRowIndex);
if (extraRowStyles != null) {
trClasses.append(" ").append(extraRowStyles);
}
}
// Build the row.
TableRowBuilder tr = startRow();
tr.className(trClasses.toString());
// Build the columns.
int columnCount = cellTable.getColumnCount();
for (int curColumn = 0; curColumn < columnCount; curColumn++) {
Column<T, ?> column = cellTable.getColumn(curColumn);
if (column == expandColumn) {
expandColumnIndex = curColumn;
column = placeholderColumn;
placeholderColumn.isSelected = isSelected;
}
// Create the cell styles.
StringBuilder tdClasses = new StringBuilder(cellStyle);
tdClasses.append(isEven ? evenCellStyle : oddCellStyle);
if (curColumn == 0) {
tdClasses.append(firstColumnStyle);
}
if (isSelected) {
tdClasses.append(selectedCellStyle);
}
// The first and last column could be the same column.
if (curColumn == columnCount - 1) {
tdClasses.append(lastColumnStyle);
}
// Add class names specific to the cell.
Context context = new Context(absRowIndex, curColumn, cellTable.getValueKey(rowValue));
String cellStyles = column.getCellStyleNames(context, rowValue);
if (cellStyles != null) {
tdClasses.append(" " + cellStyles);
}
// Build the cell.
HorizontalAlignmentConstant hAlign = column.getHorizontalAlignment();
VerticalAlignmentConstant vAlign = column.getVerticalAlignment();
TableCellBuilder td = tr.startTD();
td.className(tdClasses.toString());
if (hAlign != null) {
td.align(hAlign.getTextAlignString());
}
if (vAlign != null) {
td.vAlign(vAlign.getVerticalAlignString());
}
// Add the inner div.
DivBuilder div = td.startDiv();
div.style().outlineStyle(OutlineStyle.NONE).endStyle();
// Render the cell into the div.
renderCell(div, context, column, rowValue);
// End the cell.
div.endDiv();
td.endTD();
}
// End the row.
tr.endTR();
if (isSelected) {
buildExpandedRow(rowValue, absRowIndex, columnCount, trClasses, isEven, isSelected);
}
}
/**
* #param trClasses
*
*/
private void buildExpandedRow(T rowValue, int absRowIndex, int columnCount, StringBuilder trClasses, boolean isEven, boolean isSelected) {
TableRowBuilder tr = startRow();
tr.className(trClasses.toString());
Column<T, ?> column = expandColumn;
// Create the cell styles.
StringBuilder tdClasses = new StringBuilder(cellStyle);
tdClasses.append(isEven ? evenCellStyle : oddCellStyle);
tdClasses.append(firstColumnStyle);
if (isSelected) {
tdClasses.append(selectedCellStyle);
}
tdClasses.append(lastColumnStyle);
// Add class names specific to the cell.
Context context = new Context(absRowIndex, expandColumnIndex, cellTable.getValueKey(rowValue));
String cellStyles = column.getCellStyleNames(context, rowValue);
if (cellStyles != null) {
tdClasses.append(" " + cellStyles);
}
// Build the cell.
HorizontalAlignmentConstant hAlign = column.getHorizontalAlignment();
VerticalAlignmentConstant vAlign = column.getVerticalAlignment();
TableCellBuilder td = tr.startTD();
td.colSpan(columnCount);
td.className(tdClasses.toString());
if (hAlign != null) {
td.align(hAlign.getTextAlignString());
}
if (vAlign != null) {
td.vAlign(vAlign.getVerticalAlignString());
}
// Add the inner div.
DivBuilder div = td.startDiv();
div.style().outlineStyle(OutlineStyle.NONE).endStyle();
// Render the cell into the div.
renderCell(div, context, column, rowValue);
// End the cell.
div.endDiv();
td.endTD();
// End the row.
tr.endTR();
}

Related

I need to show different tool tip for each table cell

Please see this
This is what I want to see... I mean the tool tip
At run time I get this error message for each row that is being loaded.
The tool tip text lies in the an object and is retrieved by thisRow.getCourseTootip(i);
Number of columns in the table varies and I create them and add them to the table view thru code.
for (int courseNo = 0; courseNo < numberOfCourses; courseNo++) {
String colName = getASemesterCourse(thisSemester, courseNo).getCourseID();
TableColumn<AResultRow, String> thisColumn = new TableColumn<>(colName);
thisColumn.setPrefWidth(80);
thisColumn.setStyle("-fx-alignment: CENTER; font-weight:bold;");
String str = TableRows.get(1).getGrade(courseNo);
final int i = courseNo;
thisColumn.setCellValueFactory(cellData -> cellData.getValue().courseGradeProperty(i));
thisColumn.setCellFactory(new Callback<TableColumn<AResultRow, String>, TableCell<AResultRow, String>>() {
public TableCell<AResultRow, String> call(TableColumn<AResultRow, String> column) {
return new TableCell<AResultRow, String>() {
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setText(item);
AResultRow thisRow = new AResultRow();
thisRow = getTableView().getItems().get(getTableRow().getIndex());
final Tooltip tip= new Tooltip();
tip.setText(thisRow.getCourseTootip(i));
setTooltip(tip);
tip.setStyle("-fx-background-color: pink; -fx-text-fill: black; -fx-font: normal normal 12pt \"Times New Roman\"");
}
}
};
}
});
boolean retVal = thisTable.getColumns().addAll(thisColumn);
}
Error is
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at victoriairene.TheMainFXMLController$1$1.updateItem(TheMainFXMLController.java:434)
at victoriairene.TheMainFXMLController$1$1.updateItem(TheMainFXMLController.java:427)
Line 434 is
thisRow = getTableView().getItems().get(getTableRow().getIndex());
Text for the tool tip for this cell comes from thisRow.getCourseTootip(i).
Can someone tell me, what is wrong with my code? Which object is null ? If it is null, then how do I get to see the correct Tooltip text, in spite of getting error messages for each row ?
I have been struggling with this for one full day.
Please help and thanks in advance.
As requested by Kleopatra I am enclosing the entire Create Table function.
public void createTableForThisSemester(int thisSemester, int numberOfCourses, javafx.collections.ObservableList<AResultRow> TableRows) {
TableView<AResultRow> thisTable = new TableView<>();
thisTable.setContextMenu(contextMenu);
TableColumn<AResultRow, String> tcolRollNo = new TableColumn<>("Roll Number");
tcolRollNo.setEditable(false);
tcolRollNo.setPrefWidth(120);
TableColumn<AResultRow, String> tcolName = new TableColumn<>("Student Name");
tcolName.setEditable(false);
tcolName.setPrefWidth(350);
tcolRollNo.setCellValueFactory(cellData -> cellData.getValue().StudentIDProperty());
tcolName.setCellValueFactory(cellData -> cellData.getValue().StudentNameProperty());
boolean xyz = thisTable.getColumns().addAll(tcolRollNo, tcolName);
// TableColumn[] courseColumn = new TableColumn[numberOfCourses];
for (int courseNo = 0; courseNo < numberOfCourses; courseNo++) {
String colName = getASemesterCourse(thisSemester, courseNo).getCourseID();
TableColumn<AResultRow, String> thisColumn = new TableColumn<>(colName);
thisColumn.setPrefWidth(80);
thisColumn.setStyle("-fx-alignment: CENTER; font-weight:bold;");
String str = TableRows.get(1).getGrade(courseNo);
final int i = courseNo;
thisColumn.setCellValueFactory(cellData -> cellData.getValue().courseGradeProperty(i));
thisColumn.setCellFactory(new Callback<TableColumn<AResultRow, String>, TableCell<AResultRow, String>>() {
public TableCell<AResultRow, String> call(TableColumn<AResultRow, String> column) {
return new TableCell<AResultRow, String>() {
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setText(item);
AResultRow thisRow = new AResultRow();
thisRow = getTableView().getItems().get(getTableRow().getIndex());
final Tooltip tip= new Tooltip();
tip.setText(thisRow.getCourseTootip(i));
setTooltip(tip);
tip.setStyle("-fx-background-color: pink; -fx-text-fill: black; -fx-font: normal normal 12pt \"Times New Roman\"");
}
}
};
}
});
boolean retVal = thisTable.getColumns().addAll(thisColumn);
}
// System.out.println("# of Rows in Table [" + thisSemester + "] = " + TableRows.size());
TableColumn<AResultRow, String> tcolGPA = new TableColumn<>("GPA");
tcolGPA.setEditable(false);
tcolGPA.setPrefWidth(80);
tcolGPA.setStyle("-fx-alignment: CENTER; font-weight:bold;");
tcolGPA.setCellValueFactory(cellData -> cellData.getValue().returnStringGPA());
boolean retVal = thisTable.getColumns().addAll(tcolGPA);
thisTable.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
thisTable.setItems(TableRows);
thisTable.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> {
//Check whether item is selected and set value of selected item to Label
if (thisTable.getSelectionModel().getSelectedItem() == null) {
gRollNumber = null;
gStudentName = null;
} else {
gRollNumber = newValue.getStudentID();
gStudentName = newValue.getStudentName();
}
});
ScrollPane thisScrollPane = new ScrollPane();
thisScrollPane.setFitToWidth(true);
thisScrollPane.setFitToHeight(true);
thisScrollPane.setMinHeight((theDetails.getHeight() - 25));
thisScrollPane.setMaxHeight((theDetails.getHeight() - 25));
thisScrollPane.setMinWidth((theDetails.getWidth() - 25));
thisScrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
Tab thisTab = tabs.getTabs().get(thisSemester);
thisTab.setContent(thisScrollPane);
thisScrollPane.setContent(thisTable);
}
I am repeating the hierarchy again - please excuse.
Table view is associated with an observablelist named ATableRows which a class ATableRow.
ATableRow contains several members and one of them is an array of class ACourseResult.
I need to know the ROW number and the array index (which is actually the Table Column number for that Cell) before I can retrieve the text for the tooltip.
Thing is the code works... except for the runtime error of null pointer. I still do not understand what the CellFactory and CellValueFactories do. Sorry about that. Oracle's documents do not say what they do......
While I am at this.... I want to tell you that my TABLE is READ ONLY. Do I Have to use the Observable List ? Can't I do this by setting values directly to each cell (just a curiosity).
Thanks in advance and sorry if my questions seem dumber.
Thanks to JAMES my problem is solved.... I am enclosing the modified code for others.
for (int courseNo = 0; courseNo < numberOfCourses; courseNo++) {
String colName = getASemesterCourse(thisSemester, courseNo).getCourseID();
TableColumn<AResultRow, String> thisColumn = new TableColumn<>(colName);
thisColumn.setPrefWidth(80);
thisColumn.setStyle("-fx-alignment: CENTER; font-weight:bold;");
String str = TableRows.get(1).getGrade(courseNo);
final int i = courseNo;
thisColumn.setCellValueFactory(cellData -> cellData.getValue().courseGradeProperty(i));
thisColumn.setCellFactory(new Callback<TableColumn<AResultRow, String>, TableCell<AResultRow, String>>() {
public TableCell<AResultRow, String> call(TableColumn<AResultRow, String> column) {
return new TableCell<AResultRow, String>() {
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setText(item);
AResultRow thisRow = new AResultRow();
final int k = this.getIndex(); **// These are the changes suggested by James**
thisRow = getTableView().getItems().get(k); ***// These are the changes suggested by James***
// thisRow = getTableView().getItems().get(getTableRow().getIndex()); <- this is the old code commented out.
final Tooltip tip= new Tooltip();
tip.setText(thisRow.getCourseTootip(i));
setTooltip(tip);
tip.setStyle("-fx-background-color: pink; -fx-text-fill: black; -fx-font: normal normal 12pt \"Times New Roman\"");
}
}
};
}
});
boolean retVal = thisTable.getColumns().addAll(thisColumn);
}
The quick, and wrong, answer to the question is to point out that TableCell has a getTableRow() method, that will give you the row data without having to look it up through the underlying data via the row index.
Technically, you should give the TableCell all of the information it needs to work independently when its updateItem() method is called. This would mean restructing the data model such that the table cell is given a structure with both the displayed contents of the cell, and the text to go in the tooltip. It would appear that the AResultRow data structure has two associated lists, one with whatever shows in the cell, and the other with whatever goes into the tooltip. My suggestion would be to refactor that so that it's a single list holding objects which contain both data elements. Once you do that, the rest of the table structure becomes trivial. Here's a working example:
public class SampleTable extends Application {
private BorderPane testPane;
class TestPane extends BorderPane {
public TestPane(List<DataModel> dataItems) {
TableView<DataModel> tableView = new TableView<DataModel>();
setCenter(tableView);
TableColumn<DataModel, ClassInfo> column1 = new TableColumn<DataModel, ClassInfo>("column 1");
TableColumn<DataModel, ClassInfo> column2 = new TableColumn<DataModel, ClassInfo>("column 2");
column1.setCellValueFactory(new PropertyValueFactory<DataModel, ClassInfo>("column1Data"));
column2.setCellValueFactory(new PropertyValueFactory<DataModel, ClassInfo>("column2Data"));
column1.setCellFactory(column -> new CustomTableCell());
column2.setCellFactory(column -> new CustomTableCell());
tableView.getColumns().addAll(column1, column2);
tableView.setItems(FXCollections.observableList(dataItems));
}
}
public static void main(String[] args) {
launch(args);
}
public class CustomTableCell extends TableCell<DataModel, ClassInfo> {
#Override
protected void updateItem(ClassInfo item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
if (item != null) {
setText(item.getName());
setTooltip(new Tooltip(item.getDescription()));
}
}
}
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Task Progress Tester");
List<DataModel> dataItems = new ArrayList<DataModel>();
DataModel row1Data = new DataModel();
row1Data.setColumn1Data(new ClassInfo("row1Col1Name", "This is the description for Row1, Column 1"));
row1Data.setColumn2Data(new ClassInfo("row1Col2Name", "This is the description for Row1, Column 2"));
dataItems.add(row1Data);
DataModel row2Data = new DataModel();
row2Data.setColumn1Data(new ClassInfo("row2Col1Name", "This is the description for Row2, Column 1"));
row2Data.setColumn2Data(new ClassInfo("row2Col2Name", "This is the description for Row2, Column 2"));
dataItems.add(row2Data);
testPane = new TestPane(dataItems);
primaryStage.setScene(new Scene(testPane, 300, 250));
primaryStage.show();
}
public class DataModel {
private ObjectProperty<ClassInfo> column1Data = new SimpleObjectProperty<ClassInfo>();
private ObjectProperty<ClassInfo> column2Data = new SimpleObjectProperty<ClassInfo>();
public void setColumn2Data(ClassInfo newValue) {
column2Data.set(newValue);
}
public void setColumn1Data(ClassInfo newValue) {
column1Data.set(newValue);
}
public ObjectProperty<ClassInfo> column1DataProperty() {
return column1Data;
}
}
public class ClassInfo {
private String name;
private String description;
public ClassInfo(String name, String description) {
this.setName(name);
this.setDescription(description);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
}

GWT Custom DataGrid SelectionHandler not selecting subitems

finally I got a custom DataGrid running. It is the same like that from the showcase of gwt. So I got some subitems and some mainitems. But now I want to detect ClickEvents. After a while I found out, that I need a SelectionHandler. But after implementing it, it only select the mainitems.
Is there a way to catch the selection of the subitems?
I also set one as selected via selectionHandler.setSelected(subitem, true); and it worked great, but how do I get the selection on my subitems from the userinput/ClickEvent?
The basic code is just:
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
#Override
public void onSelectionChange(final SelectionChangeEvent event) {
File selected = ((SingleSelectionModel) selectionModel).getSelectedObject();
if(selected != null){
Window.alert(selected.getFileName());
}
}
}
});
/**
* Renders the data rows that display each contact in the table.
*/
private class CustomTableBuilder extends AbstractCellTableBuilder<File> {
private final String childCell = " " + FileTreeViewImpl.this.resources.styles().childCell();
private final String rowStyle;
private final String selectedRowStyle;
private final String cellStyle;
private final String selectedCellStyle;
public CustomTableBuilder() {
super(FileTreeViewImpl.this.fileDataGrid);
DefaultSelectionEventManager.createCustomManager(new DefaultSelectionEventManager
.WhitelistEventTranslator<File>(0));
// Cache styles for faster access.
com.google.gwt.user.cellview.client.AbstractCellTable.Style style = FileTreeViewImpl.this.fileDataGrid.getResources().style();
this.rowStyle = style.evenRow();
this.selectedRowStyle = " " + style.selectedRow();
this.cellStyle = style.cell() + " " + style.evenRowCell();
this.selectedCellStyle = " " + style.selectedRowCell();
}
#Override
protected void buildRowImpl(final File rowValue, final int absRowIndex) {
buildContactRow(rowValue, absRowIndex, false);
// Display list of files.
if (FileTreeViewImpl.this.displayFolderContent.contains(rowValue.getFileName())) {
Set<File> files = FileTreeViewImpl.this.folderMap.get(rowValue.getFileName());
for (File file : files) {
buildContactRow(file, absRowIndex, true);
}
}
}
/**
* Build a row.
*
* #param rowValue
* the file info
* #param absRowIndex
* the absolute row index
* #param isFriend
* true if this is a subrow, false if a top level row
*/
private void buildContactRow(final File rowValue, final int absRowIndex, final boolean isFriend) {
// Calculate the row styles.
SelectionModel<? super File> selectionModel = FileTreeViewImpl.this.fileDataGrid.getSelectionModel();
boolean isSelected = (selectionModel == null || rowValue == null) ? false : selectionModel.isSelected(rowValue);
StringBuilder trClasses = new StringBuilder(this.rowStyle);
if (isSelected) {
trClasses.append(this.selectedRowStyle);
}
// Calculate the cell styles.
String cellStyles = this.cellStyle;
if (isSelected) {
cellStyles += this.selectedCellStyle;
}
if (isFriend) {
cellStyles += this.childCell;
}
TableRowBuilder row = startRow();
row.className(trClasses.toString());
// Column one to expand the submenu.
TableCellBuilder td = row.startTD();
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
if (!isFriend) {
renderCell(td, createContext(0), FileTreeViewImpl.this.viewFolderContent, rowValue);
}
td.endTD();
// Filename goes here.
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
if (isFriend) {
td.text(rowValue.getFileName());
} else {
renderCell(td, createContext(1), FileTreeViewImpl.this.nameColumn, rowValue);
}
td.endTD();
// Filesize goes here.
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
if (isFriend) {
td.text(rowValue.getFileSizeAsString());
} else {
renderCell(td, createContext(2), FileTreeViewImpl.this.sizeColumn, rowValue);
}
td.endTD();
// Last Editor goes here.
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
if (isFriend) {
td.text(rowValue.getLastEditedBy());
} else {
renderCell(td, createContext(3), FileTreeViewImpl.this.editedColumn, rowValue);
}
td.endTD();
row.endTR();
}
}</code>
Greetings

CustomdataGrid is not being displayed in the browser

I have a custom datagrid which is defined as follows
public class CustomDataGrid<T> extends DataGrid<T> {
private static final int PAGE_SIZE = 10;
public CustomDataGrid(ProvidesKey<T> keysProvider) {
super(PAGE_SIZE, keysProvider);
}
public CustomDataGrid() {
super(PAGE_SIZE);
}
public void redrawRow(int absRowIndex) {
int relRowIndex = absRowIndex - getPageStart();
checkRowBounds(relRowIndex);
setRowData(absRowIndex, Collections.singletonList(getVisibleItem(relRowIndex)));
}
}
I am using ui binder and in my xml file I have defined the elements as follows
<com:CustomDataGrid ui:field="commissionListDataGrid"></com:CustomDataGrid>
Now the custom datagrid is initialised as follows
#UiField
CustomDataGrid commissionListDataGrid;
private final Set<Long> showingFriends = new HashSet<Long>();
private Column<ServiceCategorywiseCommissionDetails, String> viewFriendsColumn;
private Column<ServiceCategorywiseCommissionDetails, String> serviceType;
public ZoneCommissionListView() {
commissionListDataGrid = new CustomDataGrid<ServiceCategorywiseCommissionDetails>(new ProvidesKey<ServiceCategorywiseCommissionDetails>() {
#Override
public Object getKey(ServiceCategorywiseCommissionDetails item) {
return item == null ? null : item.getId();
}
});
commissionListDataGrid.setWidth("100%");
commissionListDataGrid.setEmptyTableWidget(new Label("Empty data"));
commissionListDataGrid.setHeight("100%");
// commissionListLayoutPanel = new SimpleLayoutPanel();
initCommissionListDataGrid();
// commissionListLayoutPanel.add(commissionListDataGrid);
//RootLayoutPanel.get().add(commissionListLayoutPanel);
}
#Override
public Widget asWidget() {
return this.widget;
}
#Override
public void setUiHandlers(ZoneCommissionListUiHandlers uiHandlers) {
this.uiHandlers = uiHandlers;
}
public void initCommissionListDataGrid() {
// View friends.
SafeHtmlRenderer<String> anchorRenderer = new AbstractSafeHtmlRenderer<String>() {
#Override
public SafeHtml render(String object) {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("(").appendEscaped(object).appendHtmlConstant(")");
return sb.toSafeHtml();
}
};
viewFriendsColumn = new Column<ServiceCategorywiseCommissionDetails, String>(new ClickableTextCell(anchorRenderer)) {
#Override
public String getValue(ServiceCategorywiseCommissionDetails object) {
if (showingFriends.contains(object.getId())) {
return "-";
} else {
return "+";
}
}
};
viewFriendsColumn.setFieldUpdater(new FieldUpdater<ServiceCategorywiseCommissionDetails, String>() {
#Override
public void update(int index, ServiceCategorywiseCommissionDetails object, String value) {
if (showingFriends.contains(object.getId())) {
showingFriends.remove(object.getId());
} else {
showingFriends.add(object.getId());
}
// Redraw the modified row.
commissionListDataGrid.redrawRow(index);
}
});
// First name.
serviceType = new Column<ServiceCategorywiseCommissionDetails, String>(new TextCell()) {
#Override
public String getValue(ServiceCategorywiseCommissionDetails object) {
return object.getServiceType();
}
};
commissionListDataGrid.setTableBuilder(new CustomTableBuilder());
commissionListDataGrid.setHeaderBuilder(new CustomHeaderBuilder());
// commissionListDataGrid.setFooterBuilder(new CustomFooterBuilder());
// GWT.log("list size is " + ContactDatabase.get().getDataProvider().getList().size());
// commissionListDataGrid.setRowData(ContactDatabase.get().getDataProvider().getList());
// Button button = new Button();
// button.setText("hello");
// commissionListLayoutPanel.add(commissionListDataGrid);
this.widget = uiBinder.createAndBindUi(this);
}
private class CustomTableBuilder extends AbstractCellTableBuilder<ServiceCategorywiseCommissionDetails> {
private final String childCell = " ";
private final String rowStyle;
private final String selectedRowStyle;
private final String cellStyle;
private final String selectedCellStyle;
#SuppressWarnings("deprecation")
public CustomTableBuilder() {
super(commissionListDataGrid);
// Cache styles for faster access.
Style style = commissionListDataGrid.getResources().style();
rowStyle = style.evenRow();
selectedRowStyle = " " + style.selectedRow();
cellStyle = style.cell() + " " + style.evenRowCell();
selectedCellStyle = " " + style.selectedRowCell();
}
public void buildRowImpl(ServiceCategorywiseCommissionDetails rowValue, int absRowIndex) {
buildServiceTypeRow(rowValue, absRowIndex, false);
GWT.log("Inside build row impl");
// Display list of friends.
if (showingFriends.contains(rowValue.getId())) {
TableRowBuilder row = startRow();
TableCellBuilder th = row.startTH();
th.text("").endTH();
TableCellBuilder th2 = row.startTH();
th2.text("Service Name").endTH();
TableCellBuilder th3 = row.startTH();
th3.text("SuperZone Commission").endTH();
TableCellBuilder th4 = row.startTH();
th4.text("Zone Commission").endTH();
row.endTR();
List<ServiceCommissionDetails> friends = rowValue.getServiceCommissionDetails();
for (ServiceCommissionDetails friend : friends) {
buildServiceCommissionDetailRow(friend, absRowIndex, true);
}
}
}
#SuppressWarnings("deprecation")
private void buildServiceTypeRow(ServiceCategorywiseCommissionDetails rowValue, int absRowIndex, boolean isFriend) {
GWT.log("inside build service Type row");
SelectionModel<? super ServiceCategorywiseCommissionDetails> selectionModel = commissionListDataGrid.getSelectionModel();
boolean isSelected = (selectionModel == null || rowValue == null) ? false : selectionModel.isSelected(rowValue);
boolean isEven = absRowIndex % 2 == 0;
StringBuilder trClasses = new StringBuilder(rowStyle);
if (isSelected) {
trClasses.append(selectedRowStyle);
}
// Calculate the cell styles.
String cellStyles = cellStyle;
if (isSelected) {
cellStyles += selectedCellStyle;
}
if (isFriend) {
cellStyles += childCell;
}
TableRowBuilder row = startRow();
row.className(trClasses.toString());
/*
* Checkbox column.
*
* This table will uses a checkbox column for selection. Alternatively, you can call dataGrid.setSelectionEnabled(true) to
* enable mouse selection.
*/
TableCellBuilder td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.endTD();
/*
* View friends column.
*
* Displays a link to "show friends". When clicked, the list of friends is displayed below the contact.
*/
td = row.startTD();
td.className(cellStyles);
if (!isFriend) {
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
renderCell(td, createContext(1), viewFriendsColumn, rowValue);
}
td.endTD();
// First name column.
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
if (isFriend) {
td.text(rowValue.getServiceType());
} else {
renderCell(td, createContext(2), serviceType, rowValue);
}
td.endTD();
// Last name column.
row.endTR();
}
#SuppressWarnings("deprecation")
private void buildServiceCommissionDetailRow(ServiceCommissionDetails rowValue, int absRowIndex, boolean isFriend) {
GWT.log("inside build service commission detail row");
// Calculate the row styles.
// boolean isSelected = (selectionModel == null || rowValue == null)
// ? false : selectionModel.isSelected(rowValue);
// boolean isEven = absRowIndex % 2 == 0;
StringBuilder trClasses = new StringBuilder(rowStyle);
// if (isSelected) {
// trClasses.append(selectedRowStyle);
// }
// Calculate the cell styles.
String cellStyles = cellStyle;
// cellStyles += selectedCellStyle;
cellStyles += childCell;
TableRowBuilder row = startRow();
row.className(trClasses.toString());
/*
* Checkbox column.
*
* This table will uses a checkbox column for selection. Alternatively, you can call dataGrid.setSelectionEnabled(true) to
* enable mouse selection.
*/
TableCellBuilder td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.endTD();
/*
* View friends column.
*
* Displays a link to "show friends". When clicked, the list of friends is displayed below the contact.
*/
// First name column.
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.text(rowValue.getServiceName());
td.endTD();
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.text(rowValue.getSuperZoneCommission());
td.endTD();
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.text(rowValue.getZoneCommission());
td.endTD();
// Last name column.
row.endTR();
}
}
private class CustomHeaderBuilder extends AbstractHeaderOrFooterBuilder<ServiceCategorywiseCommissionDetails> {
private Header<String> firstNameHeader = new TextHeader("Co mmission List");
public CustomHeaderBuilder() {
super(commissionListDataGrid, false);
setSortIconStartOfLine(false);
}
#Override
protected boolean buildHeaderOrFooterImpl() {
Style style = commissionListDataGrid.getResources().style();
String groupHeaderCell = "Header Cell";
// Add a 2x2 header above the checkbox and show friends columns.
TableRowBuilder tr = startRow();
tr.startTH().colSpan(2).rowSpan(2).className(style.header() + " " + style.firstColumnHeader());
tr.endTH();
/*
* Name group header. Associated with the last name column, so clicking on the group header sorts by last name.
*/
// Get information about the sorted column.
ColumnSortList sortList = commissionListDataGrid.getColumnSortList();
ColumnSortInfo sortedInfo = (sortList.size() == 0) ? null : sortList.get(0);
Column<?, ?> sortedColumn = (sortedInfo == null) ? null : sortedInfo.getColumn();
boolean isSortAscending = (sortedInfo == null) ? false : sortedInfo.isAscending();
// Add column headers.
tr = startRow();
buildHeader(tr, firstNameHeader, serviceType, sortedColumn, isSortAscending, false, false);
tr.endTR();
return true;
}
private void buildHeader(TableRowBuilder out, Header<?> header, Column<ServiceCategorywiseCommissionDetails, ?> column, Column<?, ?> sortedColumn, boolean isSortAscending, boolean isFirst,
boolean isLast) {
// Choose the classes to include with the element.
Style style = commissionListDataGrid.getResources().style();
boolean isSorted = (sortedColumn == column);
StringBuilder classesBuilder = new StringBuilder(style.header());
if (isFirst) {
classesBuilder.append(" " + style.firstColumnHeader());
}
if (isLast) {
classesBuilder.append(" " + style.lastColumnHeader());
}
// if (column.isSortable()) {
// classesBuilder.append(" " + style.sortableHeader());
// }
if (isSorted) {
classesBuilder.append(" " + (isSortAscending ? style.sortedHeaderAscending() : style.sortedHeaderDescending()));
}
// Create the table cell.
TableCellBuilder th = out.startTH().className(classesBuilder.toString());
// Associate the cell with the column to enable sorting of the
// column.
enableColumnHandlers(th, column);
// Render the header.
Context context = new Context(0, 2, header.getKey());
renderSortableHeader(th, context, header, isSorted, isSortAscending);
// End the table cell.
th.endTH();
}
}
public void setCommissionListDataGrid(ListDataProvider<ServiceCategorywiseCommissionDetails> dataProvider) {
GWT.log("inside set commissionListDataGrid size is " + dataProvider.getList().size());
commissionListDataGrid.setRowData(dataProvider.getList());
}
And I have a method in the presenter which calls the method set CommissionListDataGrid and sets its row value.
While doing this the data grid is not displayed. However if i add simplelayoutpanel in the following way in the constructor 'ZoneCommissionListView()'
RootPanel.get().add(commissionListLayoutPanel);
Then the data grid is displayed .What exactly am I missing .Any suggestion would be appreciated
DataGrid requires to be put in a LayoutPanel or Panel that implements
the ProvidesResize interface to be visible.
Source
And the SimpelLayoutPanel which you tested also implements the ProvidesResize Interface.

Enabling single column selection in org.eclipse.swt.widgets.Table

I have used the org.eclipse.swt.widgets.Table
Code implementation will look like this
Table table = new Table(shell, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
But i need behavior like if mouse clicked on 'Sec_1' i want only 'Sec_1' to be selected not entire row and if mouse clicked on 'First_1' i don't want it to be Highlighted(FirstColumn no selection).
Can any one help me ?
Please see this code snippet for example (http://git.eclipse.org/c/platform/eclipse.platform.ui.git/tree/examples/org.eclipse.jface.snippets/Eclipse%20JFace%20Snippets/org/eclipse/jface/snippets/viewers/Snippet036FocusBorderCellHighlighter.java):
public class Test {
private class MyContentProvider implements IStructuredContentProvider {
/*
* (non-Javadoc)
*
* #see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
public Object[] getElements(Object inputElement) {
return (MyModel[]) inputElement;
}
/*
* (non-Javadoc)
*
* #see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
public void dispose() {
}
/*
* (non-Javadoc)
*
* #see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
* java.lang.Object, java.lang.Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
public static boolean flag = true;
public class MyModel {
public int counter;
public MyModel(int counter) {
this.counter = counter;
}
public String toString() {
return "Item " + this.counter;
}
}
public class MyLabelProvider extends LabelProvider implements
ITableLabelProvider, ITableFontProvider, ITableColorProvider {
FontRegistry registry = new FontRegistry();
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
return "Column " + columnIndex + " => " + element.toString();
}
public Font getFont(Object element, int columnIndex) {
return null;
}
public Color getBackground(Object element, int columnIndex) {
return null;
}
public Color getForeground(Object element, int columnIndex) {
return null;
}
}
public Test(Shell shell) {
final TableViewer v = new TableViewer(shell, SWT.BORDER|SWT.FULL_SELECTION);
v.setLabelProvider(new MyLabelProvider());
v.setContentProvider(new MyContentProvider());
v.setCellEditors(new CellEditor[] { new TextCellEditor(v.getTable()), new TextCellEditor(v.getTable()), new TextCellEditor(v.getTable()) });
v.setCellModifier(new ICellModifier() {
public boolean canModify(Object element, String property) {
return true;
}
public Object getValue(Object element, String property) {
return "Column " + property + " => " + element.toString();
}
public void modify(Object element, String property, Object value) {
}
});
v.setColumnProperties(new String[] {"1","2","3"});
TableViewerFocusCellManager focusCellManager = new TableViewerFocusCellManager(v,new FocusCellOwnerDrawHighlighter(v));
ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(v) {
protected boolean isEditorActivationEvent(
ColumnViewerEditorActivationEvent event) {
return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
|| event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
|| (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED && event.keyCode == SWT.CR)
|| event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
}
};
TableViewerEditor.create(v, focusCellManager, actSupport, ColumnViewerEditor.TABBING_HORIZONTAL
| ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
| ColumnViewerEditor.TABBING_VERTICAL | ColumnViewerEditor.KEYBOARD_ACTIVATION);
TableColumn column = new TableColumn(v.getTable(), SWT.NONE);
column.setWidth(200);
column.setMoveable(true);
column.setText("Column 1");
column = new TableColumn(v.getTable(), SWT.NONE);
column.setWidth(200);
column.setMoveable(true);
column.setText("Column 2");
column = new TableColumn(v.getTable(), SWT.NONE);
column.setWidth(200);
column.setMoveable(true);
column.setText("Column 3");
MyModel[] model = createModel();
v.setInput(model);
v.getTable().setLinesVisible(true);
v.getTable().setHeaderVisible(true);
}
private MyModel[] createModel() {
MyModel[] elements = new MyModel[10];
for (int i = 0; i < 10; i++) {
elements[i] = new MyModel(i);
}
return elements;
}
/**
* #param args
*/
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
new Test(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}

CheckboxCell, MultiSelectionModel unwantonly reset DataGrid's data

Using GWT 2.4...
I am building upon a complex Composite dual view/edit mode implementation that is backed GWT's DataGrid and MultiSelectionModel. My goal is for a user to be able to click a checkbox in each row that they'd like to post updates for.
Here's a screenshot from a semi-functional interface:
Note the selected (highlighted) rows.
Now the problem is that when I type something in any of the cells (e.g., the first row's $ cell under the $/Mw 1 composite cell header), then click that row's checkbox (or any other row's checkbox for that matter) to select or de-select, the value gets reset to the original value when the screen's data was first requested. Not desired behavior by any stretch!
Let's take a look at my custom implementation for the grid. (Excuse the length).
public abstract class ToggleableGrid<T extends Identifiable<?>> extends Composite {
private static final int CHKBOX_COLUMN_WIDTH = App.INSTANCE.checkboxColumnWidth();
private static final DisplayMode DEFAULT_MODE = DisplayMode.VIEW;
private ProvidesKey<T> keyProvider;
private DataGrid<T> grid;
private MultiSelectionModel<T> selectionModel;
private ListDataProvider<T> dataProvider;
private int tabIndex = 0;
public ToggleableGrid() {
final DataGridConfiguration config = new DefaultDataGridConfiguration();
initGrid(config);
}
public ToggleableGrid(DataGridConfiguration config) {
initGrid(config);
}
private void initGrid(DataGridConfiguration config) {
keyProvider = new ProvidesKey<T>() {
#Override
public Object getKey(T item) {
return item == null ? null : item.getId();
}
};
grid = new DataGrid<T>(config.getPageSize(), config.getResources(), keyProvider);
// Set the message to display when the table is empty.
grid.setEmptyTableWidget(new Label(UiMessages.INSTANCE.no_results()));
initWidget(grid);
setVisible(true);
}
public void setInput(List<T> content) {
setInput(content, DEFAULT_MODE);
}
public void setInput(List<T> content, DisplayMode mode) {
resetTableColumns();
if (isInEditMode(mode)) {
// Add a selection model so we can select cells
selectionModel = new MultiSelectionModel<T>(keyProvider);
grid.setSelectionModel(selectionModel, DefaultSelectionEventManager.<T> createCheckboxManager(0));
addRowSelector();
}
dataProvider = new ListDataProvider<T>(content);
final ListHandler<T> sortHandler = new ListHandler<T>(dataProvider.getList());
grid.addColumnSortHandler(sortHandler);
initializeStructure(constructMetadata(), sortHandler, mode);
dataProvider.addDataDisplay(grid);
}
// see https://stackoverflow.com/questions/3772480/remove-all-columns-from-a-celltable
// concrete classes are forced to maintain a handle on all columns added
private void resetTableColumns() {
for (final Column<T, ?> column: allColumns()) {
grid.removeColumn(column);
}
allColumns().clear();
}
protected boolean isInEditMode(DisplayMode currentDisplayMode) {
boolean result = false;
if (currentDisplayMode.equals(DisplayMode.EDIT)) {
result = true;
}
return result;
}
protected abstract Set<Column<T, ?>> allColumns();
protected abstract TableMetadata constructMetadata();
protected abstract void initializeStructure(TableMetadata metadata, ListHandler<T> sortHandler, DisplayMode mode);
protected void setColumnHorizontalAlignment(Column<T, ?> column, HorizontalAlignmentConstant alignment) {
column.setHorizontalAlignment(alignment);
}
// TODO figure out how to add a checkbox to column header that provides select/de-select all capability
// see https://stackoverflow.com/questions/6174689/gwt-celltable-programmatically-select-checkboxcell
protected void addRowSelector() {
final Column<T, Boolean> rowSelectColumn = new Column<T, Boolean>(new CheckboxCell(true, false)) {
#Override
public Boolean getValue(T value) {
Boolean result;
// check for null value and return null;
if(value == null || value.getId() == null) {
result = null;
} else { // get value from the selection model
result = selectionModel.isSelected(value);
}
return result;
}
};
addColumn(rowSelectColumn, UiMessages.INSTANCE.select());
setColumnWidth(rowSelectColumn, CHKBOX_COLUMN_WIDTH, Unit.PX);
setColumnHorizontalAlignment(rowSelectColumn, HasHorizontalAlignment.ALIGN_CENTER);
}
protected void setColumnWidth(Column<T, ?> column, int width, Unit unit) {
grid.setColumnWidth(column, width, unit);
}
protected void addColumn(Column<T, ?> column, String columnHeaderName) {
addColumn(column, columnHeaderName, HasHorizontalAlignment.ALIGN_RIGHT);
}
protected void addColumn(Column<T, ?> column, String columnHeaderName, HorizontalAlignmentConstant alignment) {
final SafeHtmlBuilder sb = new SafeHtmlBuilder();
final String divStart = "<div align=\""+ alignment.getTextAlignString() + "\" class=\"" +UiResources.INSTANCE.style().word_wrap() + "\">";
sb.appendHtmlConstant(divStart).appendEscaped(columnHeaderName).appendHtmlConstant("</div>");
final SafeHtml header = sb.toSafeHtml();
grid.addColumn(column, header);
allColumns().add(column);
}
protected CompositeCell<T> generateCompositeCell(final List<HasCell<T, ?>> hasCells) {
final CompositeCell<T> compositeCell = new CompositeCell<T>(hasCells) {
#Override
public void render(Context context, T value, SafeHtmlBuilder sb) {
sb.appendHtmlConstant("<table><tbody><tr>");
super.render(context, value, sb);
sb.appendHtmlConstant("</tr></tbody></table>");
}
#Override
protected Element getContainerElement(Element parent) {
// Return the first TR element in the table.
return parent.getFirstChildElement().getFirstChildElement().getFirstChildElement();
}
#Override
protected <X> void render(Context context, T value,
SafeHtmlBuilder sb, HasCell<T, X> hasCell) {
final Cell<X> cell = hasCell.getCell();
sb.appendHtmlConstant("<td>");
cell.render(context, hasCell.getValue(value), sb);
sb.appendHtmlConstant("</td>");
}
};
return compositeCell;
}
// FIXME not working quite the way we'd expect, index incremented within column for each row, not each row by column
protected int nextTabIndex() {
tabIndex++;
return tabIndex;
}
protected AbstractCellTable<T> getGrid() {
return grid;
}
/**
* Gets the selected (row(s) of) data from grid (used in edit mode)
* #return the selected data (as per selection model)
*/
public List<T> getSelectedData() {
final List<T> data = new ArrayList<T>();
data.addAll(selectionModel.getSelectedSet());
return data;
}
/**
* Gets all (row(s) of) data in grid (used in edit mode)
* #return all data as list
*/
public List<T> getAllData() {
return dataProvider.getList();
}
/**
* Clears the currently selected (row(s) of) data (used in edit mode)
*/
public void clearSelectedData() {
selectionModel.clear();
grid.redraw();
}
}
So, the interesting methods to stare at above (I think) are setInput, generateCompositeCell and addRowSelector.
We initialize the grid with List data and set a display mode in setInput. It's here as well that the selection model is initialized. It uses GWT's DefaultSelectionEventManager createCheckboxManager().
I've been trying to grok the event model, but it eludes me. I've visited the following sources online, but have come up short on avenues to solving this problem.
-- https://groups.google.com/forum/?fromgroups#!topic/google-web-toolkit/k5sfURxDaVg
AbstractInputCell's getConsumedEventsImpl adds focus, blur and keydown, so this (I believe) is not a track I need to explore
-- GWT CellTable programmatically select CheckBoxCell
The various ways you can instantiate a CheckBoxCell got me curious, and I've tried many constructor argument permutations, but the one I settled on (true, false) is (I believe) the right one
Agreeing here and now (before being reprimanded) that there's perhaps some unnecessary complexity in my implementation, but I am looking for guidance nonetheless. Thanks!
Update
If it helps here's an impl of the aforementioned ToggleableGrid. If anything it gives you more detail on what goes into each CompositeCell. For details on AbstractValidatableColumn and ValidatableInputCell, see: In search of a GWT validation example... where art thou?.
public class EnergyOfferGrid extends ToggleableGrid<EnergyOfferDTO> {
public EnergyOfferGrid() {
super();
}
public EnergyOfferGrid(DataGridConfiguration config) {
super(config);
}
private static final int MAX_NUMBER_OF_MW_PRICE_POINTS = App.INSTANCE.maxNoOfMwPricePoints();
private Set<Column<EnergyOfferDTO, ?>> columns = new HashSet<Column<EnergyOfferDTO, ?>>();
#Override
protected Set<Column<EnergyOfferDTO, ?>> allColumns() {
return columns;
}
#Override
protected TableMetadata constructMetadata() {
final TableMetadata metadata = new TableMetadata();
// TODO Consider a predefined set of ReferenceData to be held in a common package
// Use Slope
metadata.addColumnMetadata(UiMessages.INSTANCE.use_slope(), new String[] {UiMessages.INSTANCE.yes(), UiMessages.INSTANCE.no()}, new String[] {"true", "false"});
return metadata;
}
#Override
protected void initializeStructure(TableMetadata metadata, ListHandler<EnergyOfferDTO> sortHandler, DisplayMode currentDisplayMode) {
addHourColumn(sortHandler);
addUseSlopeColumn(metadata, sortHandler, currentDisplayMode);
for (int i = 0; i < MAX_NUMBER_OF_MW_PRICE_POINTS; i++) { // zero-based indexing
addPriceMwColumn(i, currentDisplayMode);
}
}
protected void addHourColumn(ListHandler<EnergyOfferDTO> sortHandler) {
final Column<EnergyOfferDTO, String> hourColumn = new Column<EnergyOfferDTO, String>(new TextCell()) {
#Override
public String getValue(EnergyOfferDTO energyOffer) {
String result = "";
if (energyOffer.getId() != null) {
final String isoDateTime = energyOffer.getId().getOperatingHour();
if (isoDateTime != null && !isoDateTime.isEmpty()) {
final Date dateTime = CSTimeUtil.isoToDate(isoDateTime);
if (dateTime != null) {
result = CSTimeUtil.dateToHour(dateTime);
}
}
}
return result;
}
};
hourColumn.setSortable(true);
sortHandler.setComparator(hourColumn, new Comparator<EnergyOfferDTO>() {
#Override
public int compare(EnergyOfferDTO eo1, EnergyOfferDTO eo2) {
final String date1 = eo1.getId() != null ? eo1.getId().getOperatingHour() : "";
final String date2 = eo2.getId() != null ? eo2.getId().getOperatingHour() : "";
return date1.compareTo(date2);
}
});
// We know that the data is sorted by hour by default.
getGrid(). getColumnSortList().push(hourColumn);
addColumn(hourColumn, UiMessages.INSTANCE.hour());
setColumnWidth(hourColumn, 45, Unit.PX);
setColumnHorizontalAlignment(hourColumn, HasHorizontalAlignment.ALIGN_RIGHT);
}
protected void addUseSlopeColumn(TableMetadata metadata, ListHandler<EnergyOfferDTO> sortHandler, DisplayMode currentDisplayMode) {
final ReferenceData refData = metadata.allColumnMetadata().get(UiMessages.INSTANCE.use_slope());
Column<EnergyOfferDTO, String> useSlopeColumn;
Cell<String> cell;
if (isInEditMode(currentDisplayMode)) {
cell = new ReferenceDataBackedSelectionCell(refData);
} else {
cell = new TextCell();
}
useSlopeColumn = new Column<EnergyOfferDTO, String>(cell) {
#Override
public String getValue(EnergyOfferDTO energyOffer) {
return refData.getDisplayValueForSubmitValue(Boolean.toString(energyOffer.isSlopeUsed()));
}
};
useSlopeColumn.setSortable(true);
sortHandler.setComparator(useSlopeColumn, new Comparator<EnergyOfferDTO>() {
#Override
public int compare(EnergyOfferDTO eo1, EnergyOfferDTO eo2) {
final String slopeUsed1 = String.valueOf(eo1.isSlopeUsed());
final String slopeUsed2 = String.valueOf(eo1.isSlopeUsed());
return slopeUsed1.compareTo(slopeUsed2);
}
});
addColumn(useSlopeColumn, UiMessages.INSTANCE.use_slope());
setColumnWidth(useSlopeColumn, 75, Unit.PX);
setColumnHorizontalAlignment(useSlopeColumn, HasHorizontalAlignment.ALIGN_RIGHT);
}
protected void addPriceMwColumn(final int colIndex, DisplayMode currentDisplayMode) {
// Construct a composite cell for energy offers that includes a pair of text inputs
final List<HasCell<EnergyOfferDTO, ?>> columns = new ArrayList<
HasCell<EnergyOfferDTO, ?>>();
// this DTO is passed along so that price and mw values for new entries are kept together
final OfferPriceMwPair newOfferPriceMwPair = new OfferPriceMwPair();
// Price
final Column<EnergyOfferDTO, String> priceColumn = generatePriceColumn(colIndex, newOfferPriceMwPair, currentDisplayMode);
columns.add(priceColumn);
// MW
final Column<EnergyOfferDTO, String> mwColumn = generateMwColumn(colIndex, newOfferPriceMwPair, currentDisplayMode);
columns.add(mwColumn);
// Composite
final CompositeCell<EnergyOfferDTO> priceMwColumnInnards = generateCompositeCell(columns);
final IdentityColumn<EnergyOfferDTO> priceMwColumn = new IdentityColumn<EnergyOfferDTO>(priceMwColumnInnards);
final StringBuilder colHeader = new StringBuilder();
colHeader.append(UiMessages.INSTANCE.price_mw_header()).append(" ").append(String.valueOf(colIndex + 1));
addColumn(priceMwColumn, colHeader.toString());
setColumnWidth(priceMwColumn, 7, Unit.EM);
setColumnHorizontalAlignment(priceMwColumn, HasHorizontalAlignment.ALIGN_RIGHT);
}
protected Column<EnergyOfferDTO, String> generatePriceColumn(final int colIndex, final OfferPriceMwPair newOfferPriceMwPair, DisplayMode currentDisplayMode) {
Column<EnergyOfferDTO, String> priceColumn;
if (isInEditMode(currentDisplayMode)) {
priceColumn = new BigDecimalValidatableColumn<EnergyOfferDTO, OfferPriceMwPair>(nextTabIndex(), getGrid()) {
#Override
public String getValue(EnergyOfferDTO energyOffer) {
return obtainPriceValue(colIndex, energyOffer, false);
}
#Override
public void doUpdate(int index, EnergyOfferDTO energyOffer, String value) {
if (value != null && !value.isEmpty()) {
// number format exceptions should be caught and handled by event bus's handle method
final double valueAsDouble = NumberFormat.getDecimalFormat().parse(value);
final BigDecimal price = BigDecimal.valueOf(valueAsDouble);
final List<OfferPriceMwPair> offerPriceCurve = energyOffer.getCurve();
final OfferPriceMwPair offerPriceMwPair = offerPriceCurve.get(colIndex);
if (offerPriceMwPair == null) { // we have a new price value
newOfferPriceMwPair.setPrice(price);
offerPriceCurve.add(newOfferPriceMwPair);
} else {
offerPriceMwPair.setPrice(price);
}
}
}
#Override
protected String getPropertyName() {
return "price";
}
#Override
protected Class<OfferPriceMwPair> getPropertyOwner() {
return OfferPriceMwPair.class;
}
};
} else {
priceColumn = new Column<EnergyOfferDTO, String>(new TextCell()) {
#Override
public String getValue(EnergyOfferDTO energyOffer) {
final String result = obtainPriceValue(colIndex, energyOffer, true);
return result;
}
};
}
return priceColumn;
}
private String obtainPriceValue(final int colIndex, EnergyOfferDTO energyOffer, boolean withCurrency) {
String result = "";
if (energyOffer != null) {
final List<OfferPriceMwPair> offerPriceCurve = energyOffer.getCurve();
final int numberOfPairs = offerPriceCurve.size();
if (colIndex < numberOfPairs) {
final OfferPriceMwPair offerPriceMwPair = offerPriceCurve.get(colIndex);
if (offerPriceMwPair != null) {
final BigDecimal price = offerPriceMwPair.getPrice();
if (price != null) {
final double value = price.doubleValue();
if (withCurrency) {
result = NumberFormat.getCurrencyFormat().format(value);
} else {
result = NumberFormat.getDecimalFormat().format(value);
}
}
}
}
}
return result;
}
protected Column<EnergyOfferDTO, String> generateMwColumn(final int colIndex, final OfferPriceMwPair newOfferPriceMwPair, DisplayMode currentDisplayMode) {
Column<EnergyOfferDTO, String> mwColumn;
if (isInEditMode(currentDisplayMode)) {
mwColumn = new BigDecimalValidatableColumn<EnergyOfferDTO, PriceMwPair>(nextTabIndex(), getGrid()) {
#Override
public String getValue(EnergyOfferDTO energyOffer) {
return obtainMwValue(colIndex, energyOffer);
}
#Override
public void doUpdate(int index, EnergyOfferDTO energyOffer, String value) {
if (value != null && !value.isEmpty()) {
// number format exceptions should be caught and handled by event bus's handle method
final double valueAsDouble = NumberFormat.getDecimalFormat().parse(value);
final BigDecimal mw = BigDecimal.valueOf(valueAsDouble);
final List<OfferPriceMwPair> offerPriceCurve = energyOffer.getCurve();
final OfferPriceMwPair offerPriceMwPair = offerPriceCurve.get(colIndex);
if (offerPriceMwPair == null) { // we have a new price value
newOfferPriceMwPair.setMw(mw);
offerPriceCurve.add(newOfferPriceMwPair);
} else {
offerPriceMwPair.setMw(mw);
}
}
}
#Override
protected String getPropertyName() {
return "mw";
}
#Override
protected Class<PriceMwPair> getPropertyOwner() {
return PriceMwPair.class;
}
};
} else {
mwColumn = new Column<EnergyOfferDTO, String>(new TextCell()) {
#Override
public String getValue(EnergyOfferDTO energyOffer) {
final String result = obtainMwValue(colIndex, energyOffer);
return result;
}
};
}
return mwColumn;
}
private String obtainMwValue(final int colIndex, EnergyOfferDTO energyOffer) {
String result = "";
if (energyOffer != null) {
final List<OfferPriceMwPair> offerPriceCurve = energyOffer.getCurve();
final int numberOfPairs = offerPriceCurve.size();
if (colIndex < numberOfPairs) {
final PriceMwPair offerPriceMwPair = offerPriceCurve.get(colIndex);
if (offerPriceMwPair != null) {
final BigDecimal mw = offerPriceMwPair.getMw();
if (mw != null) {
result = NumberFormat.getDecimalFormat().format(mw);
}
}
}
}
return result;
}
}
All that custom work w.r.t. WrapperCell and CompositeValidatableColumn was unnecessary.
It turns out that there's a way you should not construct CompositeCells. See http://code.google.com/p/google-web-toolkit/issues/detail?id=5714. My CompositeCells were not receiving events. So, I changed the way I construct them in ToggleableGrid.
protected CompositeCell<T> generateCompositeCell(final List<HasCell<T, String>> hasCells) {
final CompositeCell<T> compositeCell = new CompositeCell<T>(hasCells) {
// to not run afoul of http://code.google.com/p/google-web-toolkit/issues/detail?id=5714
#Override
public void render(Context context, T value, SafeHtmlBuilder sb) {
sb.appendHtmlConstant("<div style=\"display: inline\">");
super.render(context, value, sb);
sb.appendHtmlConstant("</div>");
}
#Override
protected Element getContainerElement(Element parent) {
// Return the first element in the DIV.
return parent.getFirstChildElement();
}
};
return compositeCell;
}
After that change and incorporating my other validation-oriented classes: ValidatableFieldUpdater, AbstractValidatableColumn (and derivatives), ValidatableInputField and ConversionResult, life couldn't be more grand!