gwt cell table dynamic columns - sorting - gwt

You can represent your "rows" as List<String> instances, you have to change your parameterization from String to List in your Grid, Column and data provider; and of course you have to call updateRowData with a List<List<String>>, not a List<String>.
You also need one Column instance per column, taking the value out of the List by index:
class IndexedColumn extends Column<List<String>, String> {
private final int index;
public IndexedColumn(int index) {
super(new EditTextCell());
this.index = index;
}
#Override
public String getValue(List<String> object) {
return object.get(this.index);
}
}
How do i add sorting to this example. I tried a ListHandler but not sure how to compare List<String>. Any help is appreciated.

You need to add a ListHandler to each column you want to sort separately. Kind of like this:
You'll have to add a getter method to IndexedColumn for the index:
class IndexedColumn extends Column<List<String>, String> {
private final int index;
public IndexedColumn(int index) {
super(new EditTextCell());
this.index = index;
}
#Override
public String getValue(List<String> object) {
return object.get(this.index);
}
public int getIndex(){
return index;
}
}
Then you'll need to add a ListHandler to the CellTable:
ListHandler<List<String>> columnSortHandler = new ListHandler<List<String>>(list);
columnSortHandler.setComparator(columnName, new Comparator<List<String>>() {
public int compare(List<String> o1, List<String> o2) {
if (o1 == o2) {
return 0;
}
// Compare the column.
if (o1 != null) {
int index = columnName.getIndex();
return (o2 != null) ? o1.get(index).compareTo(o2.get(index)) : 1;
}
return -1;
}
});
table.addColumnSortHandler(columnSortHandler);
In the example above list is the List<List<String>> object. The columnName is the Column object. You'll have to do this for every column you want to sort.
Don't forget to also call .setSortable(true) on each of the columns that you will sort.
A good basic example of column sorting can be found here. The code above is based on this example but I used your index in IndexedColumn in order to get the proper String for the column to do the comparison.

Here is the data grid code
indexedColumn.setSortable(true);
sortHandler.setComparator((Column<T, ?>) indexedColumn, (Comparator<T>) indexedColumn.getComparator(true));
Here is the actual class
public class IndexedColumn extends Column<List<String>, String>
{
private Comparator<List<String>> forwardComparator;
private Comparator<List<String>> reverseComparator;
private final int index;
public IndexedColumn(int index)
{
super(new TextCell());
this.index = index;
}
#Override
public String getValue(List<String> object)
{
return object.get(index);
}
public Comparator<List<String>> getComparator(final boolean reverse)
{
if (!reverse && forwardComparator != null)
{
return forwardComparator;
}
if (reverse && reverseComparator != null)
{
return reverseComparator;
}
Comparator<List<String>> comparator = new Comparator<List<String>>()
{
public int compare(List<String> o1, List<String> o2)
{
if (o1 == null && o2 == null)
{
return 0;
}
else if (o1 == null)
{
return reverse ? 1 : -1;
}
else if (o2 == null)
{
return reverse ? -1 : 1;
}
// Compare the column value.
String c1 = getValue(o1);
String c2 = getValue(o2);
if (c1 == null && c2 == null)
{
return 0;
}
else if (c1 == null)
{
return reverse ? 1 : -1;
}
else if (c2 == null)
{
return reverse ? -1 : 1;
}
int comparison = ((String) c1).compareTo(c2);
return reverse ? -comparison : comparison;
}
};
if (reverse)
{
reverseComparator = comparator;
}
else
{
forwardComparator = comparator;
}
return comparator;
}
}

Related

Type safety / List is a raw type

Hi i'm getting this warning and I need help on how to fix it, it appears under my combine method which merges two existing lists together, the warning is
Type safety: The expression of type List needs unchecked conversion to conform to List and List is a raw type. References to generic type List should be paramaterized.
For my equals method, my List class says that it's a raw type as well
public class List<T> implements ListInterface<T> {
private int lastIndex;
private Object[] elements;
public List() {
elements = new Object[10];
lastIndex = 0;
}
public List<T> combine(List<T> list2) {
List<T> l = new List(); // This is where the warning is underlined
try {
for (int i = 1; i <= lastIndex; i++)
l.add (retrieve (i));
for (int i = 1; i <= list2.lastIndex; i++)
l.add (list2.retrieve (i));
}
catch (ListException e) {
System.out.println("Should not occur (Combine)");
}
return l;
}
public boolean equals(Object list) {
if (list == null) {
return false;
}
List myList = (List)list; // cast to type List // Under each List, it says it is a raw type. References to generic type List<T> should be paramaterized.
if (myList.getClass() != this.getClass()) {
return false;
}
if (myList.length() != this.length()) {
return false;
}
try {
for (int pos = 1; pos <= lastIndex; pos++) {
if (!myList.retrieve(pos).equals(this.retrieve(pos))) {
return false;
}
}
}
catch (ListException e) {
System.out.println("Should not occur");
}
return true;
}
}
Thank you!

GWT- In celltable column checkboxcell select all records i want select display record

Frineds,
I am using celltable and their is one column which I put in table header for select all record option and also I am using pager which showing max 15 record in one page. when I clicked on selectall option it will select all records which are present page no 2,3,4,.... in short all records get selected(if total records is 100 it's selected 100 records).so i want only select display page records not all...
ref code is -
final SelectionModel < GenericFirewallRule > selectionModel =
new MultiSelectionModel < GenericFirewallRule > ();
deleteRuleCellTable.setSelectionModel(selectionModel,DefaultSelectionEventManager. < GenericFirewallRule > createCheckboxManager());
// CheckboxCell cbForHeader = new CheckboxCell();
Column < GenericFirewallRule, Boolean > checkColumn = new Column < GenericFirewallRule, Boolean > (
new CheckboxCell()) {#Override
public Boolean getValue(GenericFirewallRule object) {
if(object == null || object.getRuleNumber() == null){
return null;
}else{
if (selectionModel.isSelected(object)) {
if (!ruleListForDelete.contains(object)) {
ruleListForDelete.add(object);
}
} else {
if (ruleListForDelete.contains(object)) {
ruleListForDelete.remove(object);
}
}
System.out.println("ruleListForDelete : " + ruleListForDelete);
return selectionModel.isSelected(object);
}
}
};
Please suggest me solutions....
You can do something like this:
selectAllHeader = new Header<Boolean>(new HeaderCheckbox()) {
#Override
public Boolean getValue() {
for (T item : getVisibleItems()) {
if (!getSelectionModel().isSelected(item)) {
return false;
}
}
return getVisibleItems().size() > 0;
}
};
selectAllHeader.setUpdater(new ValueUpdater<Boolean>() {
#Override
public void update(Boolean value) {
for (T object : getVisibleItems()) {
getSelectionModel().setSelected(object, value);
}
}
});
public class HeaderCheckbox extends CheckboxCell {
private final SafeHtml INPUT_CHECKED = SafeHtmlUtils.fromSafeConstant("<input type=\"checkbox\" tabindex=\"-1\" checked/>");
private final SafeHtml INPUT_UNCHECKED = SafeHtmlUtils.fromSafeConstant("<input type=\"checkbox\" tabindex=\"-1\"/>");
public HeaderCheckbox() {
}
#Override
public void render(Context context, Boolean value, SafeHtmlBuilder sb) {
if (value != null && value) {
sb.append(INPUT_CHECKED);
} else {
sb.append(INPUT_UNCHECKED);
}
}
}

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!

SimplePager row count is working incorrectly

I'm using SimplePager and I want to show 12 items (users) per page. My entire data set is 20 items.
The problem is that the first page (correctly) shows items 1-12, but the second page shows items 9-20. I want the second page to show items 13-20.
What's going wrong?
Here is my code:
CellTable<User> cellTable = new CellTable<User>();
SimplePager pager = new SimplePager(TextLocation.CENTER);
pager.setDisplay(cellTable);
pager.setPageSize(12);
ListDataProvider<User> dataProvider = new ListDataProvider<User>();<br>
dataProvider.setList(USERSList);
dataProvider.addDataDisplay(cellTable);
Thank you in advance!
Setting
setRangeLimited(false)
will always show a next page.
Instead, I have rangeLimited at true and I've overridden the following method for this :
#Override
public void setPageStart(int index) {
if (getDisplay() != null) {
Range range = getDisplay().getVisibleRange();
int pageSize = range.getLength();
// Removed the min to show fixed ranges
//if (isRangeLimited && display.isRowCountExact()) {
// index = Math.min(index, display.getRowCount() - pageSize);
//}
index = Math.max(0, index);
if (index != range.getStart()) {
getDisplay().setVisibleRange(index, pageSize);
}
}
}
Try setting:
setRangeLimited(false)
More details:
http://groups.google.com/group/google-web-toolkit/browse_thread/thread/45e77082b796281d/d5101729e83a74ff?lnk=gst&q=pager+last+page#d5101729e83a74ff
#fbfcn and #MasterUZ's solution works, with a few slight modifications to make it comply with GWT 2.4's SimplePager:
public class MySimplePager extends SimplePager {
public MySimplePager() {
this.setRangeLimited(true);
}
public MySimplePager(TextLocation location, Resources resources, boolean showFastForwardButton, int fastForwardRows, boolean showLastPageButton) {
super(location, resources, showFastForwardButton, fastForwardRows, showLastPageButton);
this.setRangeLimited(true);
}
public void setPageStart(int index) {
if (this.getDisplay() != null) {
Range range = getDisplay().getVisibleRange();
int pageSize = range.getLength();
if (!isRangeLimited() && getDisplay().isRowCountExact()) {
index = Math.min(index, getDisplay().getRowCount() - pageSize);
}
index = Math.max(0, index);
if (index != range.getStart()) {
getDisplay().setVisibleRange(index, pageSize);
}
}
}
}
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.view.client.Range;
public class MySimplePager extends SimplePager {
public MySimplePager() {
this.setRangeLimited(true);
}
public MySimplePager(TextLocation location, Resources resources, boolean showFastForwardButton, int fastForwardRows, boolean showLastPageButton) {
super(location, resources, showFastForwardButton, fastForwardRows, showLastPageButton);
this.setRangeLimited(true);
}
#Override
public void setPageStart(int index) {
if (getDisplay() != null) {
Range range = getDisplay().getVisibleRange();
int pageSize = range.getLength();
if (!isRangeLimited() && getDisplay().isRowCountExact()) {
index = Math.min(index, getDisplay().getRowCount() - pageSize);
}
index = Math.max(0, index);
if (index != range.getStart()) {
getDisplay().setVisibleRange(index, pageSize);
}
}
}
}

Solution for Numeric Text Field in GWT

I need a text field very similar in behavior to Gxt's NumberField. Unfortunately I am not using Gxt in my application and GWT 2.0 does not have a Numeric text field implementation as yet.
So that currently leaves me with an option to simulate a NumberField by filtering out non-numeric keystrokes using a keyboardHandler.
Is this the the best way to approach the problem? Does anyone here have a better solution/approach in mind?
Thanks in advance :)
Here you can find the code that I use in one of my classes. The features are much more limited that those of GXT, but should put you in the proper track.
It's a really basic widget, but does what I need to.
public class ValueTextBox extends TextBox {
private int min = 0;
private int max = 100;
private boolean minConstrained = true;
private boolean maxConstrained = true;
private int minDigits = 1;
private int step = 1;
private KeyUpHandler keyUpHandler = new KeyUpHandler() {
#Override
public void onKeyUp(KeyUpEvent event) {
if (isReadOnly() || !isEnabled()) {
return;
}
int keyCode = event.getNativeEvent().getKeyCode();
boolean processed = false;
switch (keyCode) {
case KeyCodes.KEY_LEFT:
case KeyCodes.KEY_RIGHT:
case KeyCodes.KEY_BACKSPACE:
case KeyCodes.KEY_DELETE:
case KeyCodes.KEY_TAB:
if (getText().isEmpty()) {
setValue(formatValue(min));
}
return;
case KeyCodes.KEY_UP:
if (step != 0) {
increaseValue();
processed = true;
}
break;
case KeyCodes.KEY_DOWN:
if (step != 0) {
decreaseValue();
processed = true;
}
break;
}
if (processed) {
cancelKey();
}
}
};
private KeyPressHandler keyPressHandler = new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
if (isReadOnly() || !isEnabled()) {
return;
}
int keyCode = event.getNativeEvent().getKeyCode();
switch (keyCode) {
case KeyCodes.KEY_LEFT:
case KeyCodes.KEY_RIGHT:
case KeyCodes.KEY_BACKSPACE:
case KeyCodes.KEY_DELETE:
case KeyCodes.KEY_TAB:
case KeyCodes.KEY_UP:
case KeyCodes.KEY_DOWN:
return;
}
int index = getCursorPos();
String previousText = getText();
String newText;
if (getSelectionLength() > 0) {
newText = previousText.substring(0, getCursorPos())
+ event.getCharCode()
+ previousText.substring(getCursorPos()
+ getSelectionLength(), previousText.length());
} else {
newText = previousText.substring(0, index)
+ event.getCharCode()
+ previousText.substring(index, previousText.length());
}
cancelKey();
setValue(newText, true);
}
};
public ValueTextBox(int value) {
this(value, 0, 100);
}
public ValueTextBox(int value, int min, int max) {
this(value, min, max, true);
}
public ValueTextBox(int value, int min, int max, boolean constrained) {
this(value, min, max, constrained, constrained);
}
public ValueTextBox(int value, int min, int max, boolean minConstrained,
boolean maxConstrained) {
super();
addKeyPressHandler(keyPressHandler);
addKeyUpHandler(keyUpHandler);
this.min = min;
this.max = max;
this.minConstrained = minConstrained;
this.maxConstrained = maxConstrained;
setValue(formatValue(value), false);
setTextAlignment(TextBoxBase.ALIGN_CENTER);
setStyleName(Resources.INSTANCE.css().fwFormEntry());
}
public void setMinDigits(int minDigits) {
if (minDigits > 0) {
this.minDigits = minDigits;
String value = getText();
long newValue = parseValue(value);
setText(formatValue(newValue));
}
}
public void setSteps(int step) {
this.step = step;
}
protected void increaseValue() {
if (step != 0) {
String value = getText();
long newValue = parseValue(value);
newValue += step;
if (maxConstrained && (newValue > max)) {
return;
}
setValue(formatValue(newValue));
}
}
protected void decreaseValue() {
if (step != 0) {
String value = getText();
long newValue = parseValue(value);
newValue -= step;
if (minConstrained && (newValue < min)) {
return;
}
setValue(formatValue(newValue));
}
}
/**
* #param value
* the value to format
* #return the formatted value
*/
protected String formatValue(long value) {
String newValue = String.valueOf(value);
if (minDigits > newValue.length()) {
String leading = StringUtils.repeat("0", (minDigits - newValue
.length()));
newValue = leading + newValue;
}
return newValue;
}
#Override
public void setValue(String value) {
setValue(value, false);
}
#Override
public void setValue(String value, boolean fireEvents) {
try {
long newValue = parseValue(value);
if ((maxConstrained && (newValue > max))
|| (minConstrained && (newValue < min))) {
return;
}
String prevText = getValue();
super.setText(formatValue(newValue));
if (fireEvents) {
ValueChangeEvent.fireIfNotEqual(this, getValue(), prevText);
}
} catch (Exception ex) {
// Do Nothing
System.out.println(ex.getMessage());
}
}
/**
* #param value
* the value to parse
* #return the parsed value
*/
protected long parseValue(String value) {
return Long.valueOf(value);
}
}
Update: The code is available in https://github.com/ctasada/GWT-Eureka
Here is a simple KeyPressHandler to allow the user to input decimal numbers;
public void onKeyPress(KeyPressEvent event){
TextBox sender = (TextBox)event.getSource();
if (sender.isReadOnly() || !sender.isEnabled()) {
return;
}
Character charCode = event.getCharCode();
int unicodeCharCode = event.getUnicodeCharCode();
// allow digits, '.' and non-characters
if (!(Character.isDigit(charCode) || charCode == '.' || unicodeCharCode == 0)){
sender.cancelKey();
}
}
Don't know when these classes were added to GWT, but they work fine for me without any extra code:
com.google.gwt.user.client.ui.DoubleBox
com.google.gwt.user.client.ui.IntegerBox
com.google.gwt.user.client.ui.LongBox
For more advanced validation you may want to overwrite their base class ValueBox with some custom Parser...
Here is my implementation of NumberField. Very similar in functionality to Carlos's version, but with additional support for decimal input and non-numeric key filtering.
public class NumberBox extends TextBox
{
private boolean isDecimal = false;
public NumberBox( )
{
}
public boolean isDecimal( )
{
return isDecimal;
}
public void setDecimal( boolean isDecimal )
{
this.isDecimal = isDecimal;
}
public Integer getIntegerValue( )
{
return ( StringUtil.isEmpty( getSanitizedValue( ) ) ) ? null : Integer.parseInt( getSanitizedValue( ) );
}
#Override
protected void initialize( )
{
super.initialize( );
addStyleName( "number" );
this.addKeyPressHandler( new KeyPressHandler( )
{
public void onKeyPress( KeyPressEvent event )
{
if ( !isEnabled( ) || isReadOnly( ) )
return;
int keyCode = event.getNativeEvent( ).getKeyCode( );
// allow special keys
if ( ( keyCode == KeyCodes.KEY_BACKSPACE )
|| ( keyCode == KeyCodes.KEY_DELETE )
|| ( keyCode == KeyCodes.KEY_ENTER ) || ( keyCode == KeyCodes.KEY_ESCAPE ) || ( keyCode == KeyCodes.KEY_RIGHT )
|| ( keyCode == KeyCodes.KEY_LEFT ) || ( keyCode == KeyCodes.KEY_TAB ) )
return;
// check for decimal '.'
if ( isDecimal( ) && '.' == (char)keyCode && !getValue( ).contains( "." ) )
return;
// filter out non-digits
if ( Character.isDigit( charCode ) )
return;
cancelKey( );
}
} );
}
}
PS: Superclass TextBox is a custom class extending GWT TextBox with some additional application specific features. The method initialize() is basically invoked inside the TextBox constructor, and getSanitizedValue does some basic sanity checks with trimming.
Carlos Tasada answer works, but contains a bug: you should add event.isShiftKeyDown() check in onKeyPress handler before switch/case block. It will pass some symbols like '(' otherwise.
Based on Julian Downes answer you can do this:
text.addKeyPressHandler(new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
TextBox sender = (TextBox) event.getSource();
if (sender.isReadOnly() || !sender.isEnabled()) {
return;
}
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER){
return;
}
Character charCode = event.getCharCode();
try{
Double.parseDouble(sender.getText().concat(charCode.toString()));
}
catch(Exception e){
sender.cancelKey();
}
}
});