CustomdataGrid is not being displayed in the browser - gwt

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.

Related

GXT 3.1.0 - Sorting dropdown missing from Grid Header

The code below creates 2 tabs.
Each tab has a grid with 1 column.
In the first tab the table header displays the dropdown with hide/show columns and sort.
In the second tab the dropdown is missing from the table header.
What am I doing wrong?
Thanks
public void onModuleLoad()
{
Grid table1 = createTable();
Grid table2 = createTable();
TabPanel tabPanel = new TabPanel();
tabPanel.add(table1, "Grid 1");
tabPanel.add(table2, "Grid 2");
RootLayoutPanel.get().add(tabPanel);
}
Grid createTable()
{
ColumnConfig<HashMap, String> nameCol = new ColumnConfig<HashMap, String>(
new ValueProvider<HashMap, String>()
{
#Override
public String getValue(HashMap object)
{
return (String) object.get("COL1");
}
#Override
public void setValue(HashMap object, String value)
{
object.put("COL1", value);
}
#Override
public String getPath()
{
// TODO Auto-generated method stub
return "1";
}
}, 200, SafeHtmlUtils.fromTrustedString("<b>Column 1</b>"));
List<ColumnConfig<HashMap, ?>> l = new ArrayList<ColumnConfig<HashMap, ?>>();
l.add(nameCol);
ColumnModel<HashMap> cm = new ColumnModel<HashMap>(l);
ModelKeyProvider<HashMap> modelKeyProvider = new ModelKeyProvider<HashMap>()
{
#Override
public String getKey(HashMap item)
{
return (String) item.get("COL1");
}
};
ListStore<HashMap> store = new ListStore<HashMap>(modelKeyProvider);
store.addAll(getStocks());
Grid table = new Grid(store, cm);
return table;
}
public static List<HashMap> getStocks()
{
List<HashMap> stocks = new ArrayList<HashMap>();
for (int i = 0; i < 1000; i++)
{
HashMap hashMap = new HashMap();
hashMap.put("COL1", "Line: " + i);
stocks.add(hashMap);
}
return stocks;
}
Looks like that the little button with the dropdown has 0 height. It must be because it's inside a tab that is not visible.
Refreshing the header solves this.
TabPanel tabPanel = new TabPanel();
tabPanel.addSelectionHandler(new SelectionHandler<Widget>()
{
#Override
public void onSelection(SelectionEvent<Widget> event)
{
if(table1.getView() != null && table1.getView().getHeader() != null)
table1.getView().getHeader().refresh();
}
});

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

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();
}
}

GWT sinkEvents in hosted mode

I extends a gwt celltable to create a custom celltable, i register the sinkevents ie onmouseover/onmouseout.
when you hover on the row of the table the row data is populated on the hover wiget(custom hover popup panel).
its works as it supose to do on development mode but once deployed on tomcat when you move the mouse over different rows on the celltable it
does not update the hover data on the popup panel unless you click away from the table(loose focus) and the hover again on the row.
public class MyCellTable<T> extends CellTable<T> {
private Tooltip popup = new Tooltip();
private List<String> tooltipHiddenColumn = new ArrayList<String>();
private boolean showTooltip;
public MyCellTable() {
super();
sinkEvents(Event.ONMOUSEOVER | Event.ONMOUSEOUT);
}
#Override
public void onBrowserEvent2(Event event) {
super.onBrowserEvent2(event);
if (isShowTooltip()) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEOUT: {
popup.hide(true);
break;
}
case Event.ONMOUSEOVER: {
popup.setAutoHideEnabled(true);
showToolTip(event);
break;
}
}
}
}
private void showToolTip(final Event event) {
EventTarget eventTarget = event.getEventTarget();
if (!Element.is(eventTarget)) {
return;
}
final Element target = event.getEventTarget().cast();
// Find the cell where the event occurred.
TableCellElement tableCell = findNearestParentCell(target);
if (tableCell == null) {
return;
}
Element trElem = tableCell.getParentElement();
if (trElem == null) {
return;
}
TableRowElement tr = TableRowElement.as(trElem);
Element sectionElem = tr.getParentElement();
if (sectionElem == null) {
return;
}
TableSectionElement section = TableSectionElement.as(sectionElem);
if (section == getTableHeadElement()) {
return;
}
NodeList<TableCellElement> cellElements = tr.getCells().cast();
NodeList<TableCellElement> headers = getTableHeadElement().getRows().getItem(0).getCells().cast();
popup.getGrid().clear(true);
popup.getGrid().resizeRows(cellElements.getLength());
for (int i = 0; i < cellElements.getLength(); i++) {
if (getTooltipHiddenColumn().indexOf(headers.getItem(i).getInnerHTML()) == -1) {
TableCellElement tst = TableCellElement.as(cellElements.getItem(i));
popup.getGrid().setHTML(i, 0, headers.getItem(i).getInnerHTML());
popup.getGrid().setHTML(i, 1, tst.getInnerHTML());
}
}
// Here the constant values are used to give some gap between mouse pointer and popup panel
popup.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
public void setPosition(int offsetWidth, int offsetHeight) {
int left = event.getClientX() + 5;
int top = event.getClientY() + 5;
if ((offsetHeight + top + 20) > Window.getClientHeight()) {
top = top - offsetHeight - 10;
}
popup.setPopupPosition(left, top);
}
});
popup.show();
}
public ArrayList<ReorderColumnsDetails> getColumnsHeaders(int index){
ArrayList<ReorderColumnsDetails> column = new ArrayList<ReorderColumnsDetails>();
NodeList<TableCellElement> headers = getTableHeadElement().getRows().getItem(0).getCells().cast();
for (int i = 0; i < index; i++) {
ReorderColumnsDetails clm = new ReorderColumnsDetails();
clm.setHearder(headers.getItem(i).getInnerHTML().toString());
clm.setItemIndex(i);
column.add(clm);
}
return column;
}
private TableCellElement findNearestParentCell(Element elem) {
while ((elem != null) && (elem != getElement())) {
String tagName = elem.getTagName();
if ("td".equalsIgnoreCase(tagName) || "th".equalsIgnoreCase(tagName)) {
return elem.cast();
}
elem = elem.getParentElement();
}
return null;
}
/**
* Specify Name of the column's which is not to shown in the Tooltip
*/
public List<String> getTooltipHiddenColumn() {
return tooltipHiddenColumn;
}
/**
* Set title to tooltip
*
* #param title
*/
public void setTooltipTitle(String title) {
popup.setHTML(title);
}
public boolean isShowTooltip() {
return showTooltip;
}
public void setShowTooltip(boolean showTooltip) {
this.showTooltip = showTooltip;
}
}

Building a custom row on demand with GWT CellTableBuilder

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();
}