GWT CellList with dynamic DataProvider - gwt

Is it possible to make a standard CellList, that he was working with a dynamic DataProvider?
On the likeness of the search engine Google
I leaf through the pages, and CellList pulls information from the server .
In the standard example in the beginning is full DataProvider
Number of lines per page - 10
The number of items I can get from the server.

Since the data are coming from the server every time you press Next or Previous you can use Async Data Provider.
Here is an example
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import com.google.gwt.cell.client.DateCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
public class CellTableExample implements EntryPoint {
/**
* A simple data type that represents a contact.
*/
private static class Contact {
private final String address;
private final Date birthday;
private final String name;
public Contact(String name, Date birthday, String address) {
this.name = name;
this.birthday = birthday;
this.address = address;
}
}
/**
* The list of data to display.
*/
#SuppressWarnings("deprecation")
private static final List<Contact> CONTACTS = Arrays.asList(
new Contact("John", new Date(80, 4, 12), "123 Abc Avenue"),
new Contact("Joe", new Date(85, 2, 22), "22 Lance Ln"),
new Contact("Tom", new Date(85, 3, 22), "33 Lance Ln"),
new Contact("Jack", new Date(85, 4, 22), "44 Lance Ln"),
new Contact("Tim", new Date(85, 5, 22), "55 Lance Ln"),
new Contact("Mike", new Date(85, 6, 22), "66 Lance Ln"),
new Contact("George", new Date(46, 6, 6),"77 Lance Ln"));
public void onModuleLoad() {
// Create a CellTable.
final CellTable<Contact> table = new CellTable<Contact>();
// Display 3 rows in one page
table.setPageSize(3);
// Add a text column to show the name.
TextColumn<Contact> nameColumn = new TextColumn<Contact>() {
#Override
public String getValue(Contact object) {
return object.name;
}
};
table.addColumn(nameColumn, "Name");
// Add a date column to show the birthday.
DateCell dateCell = new DateCell();
Column<Contact, Date> dateColumn = new Column<Contact, Date>(dateCell) {
#Override
public Date getValue(Contact object) {
return object.birthday;
}
};
table.addColumn(dateColumn, "Birthday");
// Add a text column to show the address.
TextColumn<Contact> addressColumn = new TextColumn<Contact>() {
#Override
public String getValue(Contact object) {
return object.address;
}
};
table.addColumn(addressColumn, "Address");
// Associate an async data provider to the table
// XXX: Use AsyncCallback in the method onRangeChanged
// to actaully get the data from the server side
AsyncDataProvider<Contact> provider = new AsyncDataProvider<Contact>() {
#Override
protected void onRangeChanged(HasData<Contact> display) {
int start = display.getVisibleRange().getStart();
int end = start + display.getVisibleRange().getLength();
end = end >= CONTACTS.size() ? CONTACTS.size() : end;
List<Contact> sub = CONTACTS.subList(start, end);
updateRowData(start, sub);
}
};
provider.addDataDisplay(table);
provider.updateRowCount(CONTACTS.size(), true);
SimplePager pager = new SimplePager();
pager.setDisplay(table);
VerticalPanel vp = new VerticalPanel();
vp.add(table);
vp.add(pager);
// Add it to the root panel.
RootPanel.get().add(vp);
}
}
// Associate an async data provider to the table
AsyncDataProvider<Contact> provider = new AsyncDataProvider<Contact>() {
#Override
protected void onRangeChanged(HasData<Contact> display) {
final int start = display.getVisibleRange().getStart();
int length = display.getVisibleRange().getLength();
AsyncCallback<List<Contact>> callback = new AsyncCallback<List<Contact>>() {
#Override
public void onFailure(Throwable caught) {
Window.alert(caught.getMessage());
}
#Override
public void onSuccess(List<Contact> result) {
updateRowData(start, result);
}
};
// The remote service that should be implemented
remoteService.fetchPage(start, length, callback);
}
};

Related

CheckBoxTableCell select entire column

I can not get the value of the checkbox, whether it is selected or not.
I can not select or deselect the entire column of CheckBoxTableCell
//CLASS MODELO
public class Cidade{
private Integer codigo;
private String descricao;
public AAA(Integer codigo, String descricao) {
super();
this.codigo = codigo;
this.descricao = descricao;
}
public Integer getCodigo() {
return codigo;
}
public String getDescricao() {
return descricao;
}
}
//CREATION OF COLUMNS OF TABLEVIEW
TableView tbView = new TableView();
tbView.setEditable(true);
TableColumn colCheck = new TableColumn();
colCheck.setCellFactory(CheckBoxTableCell.forTableColumn(colCheck));
CheckBox cbk = new CheckBox();
cbk.selectedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
// TODO Auto-generated method stub
if (!tbView.getItems().isEmpty())
if (newValue)
for (int i = 0; i < tbView.getItems().size(); i++) {
((CheckBox) ((TableColumn) tbView.getColumns().get(0)).getGraphic()).selectedProperty().get();
}
}
});
colCheck.setGraphic(cbk);
tbView.getColumns().add(colCheck);
TableColumn colCode = new TableColumn("Codido");
colCode.setCellValueFactory(new PropertyValueFactory("codigo"));
TableColumn colDescricao = new TableColumn("Descricao");
colCode.setCellValueFactory(new PropertyValueFactory("descricao"));
tbView.getColumns().addAll(colCode,colDescricao);
The CheckBoxTableCell expects a selectedStateCallback, which is a function mapping the row index to an ObservableValue<Boolean> that determines if the check box should be checked. If the supplied observable value is also a WritableValue<Boolean>, then when the user checks or unchecks the check box, the value will be updated.
The simplest case for this is when the model for the table has a boolean property which is represented by the check box. However, this doesn't have to be the case. For example, you could create a map from your table items to a boolean property, and use the properties in that map for the selected state of the check boxes:
Map<T, BooleanProperty> checkedRows = new HashMap<>();
checkColumn.setCellFactory(CheckBoxTableCell.forTableColumn(i ->
checkedRows.computeIfAbsent(table.getItems().get(i), p -> new SimpleBooleanProperty())));
Here you would replace T with the actual type of your table.
You probably want to ensure the map doesn't hold references to items that are no longer part of your table:
// clear obsolete table items from map:
table.getItems().addListener((Change<? extends T> c) -> {
if (c.wasRemoved()) {
c.getRemoved().forEach(checkedRows::remove);
}
});
Now you would just use the map to check for which items are checked:
T item = ... ;
boolean itemIsChecked = checkedRows.getOrDefault(item, new SimpleBooleanProperty(false)).get() ;
or get all the checked items with
List<T> checkedItems = checkedRows.entrySet().stream()
.filter(e -> e.getValue().get())
.map(Entry::getKey)
.collect(Collectors.toList());
You can select everything with
table.getItems().forEach(item ->
checkedRows.computeIfAbsent(item , item -> new SimpleBooleanProperty()).set(true));
and similarly deselect by setting to false.
Here is a complete SSCCE using the usual address book example:
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener.Change;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class TableViewWithCheckBoxColumn extends Application {
#Override
public void start(Stage primaryStage) {
TableView<Person> table = new TableView<>();
table.setEditable(true);
TableColumn<Person, Void> checkColumn = new TableColumn<>();
table.getColumns().add(checkColumn);
Map<Person, BooleanProperty> checkedRows = new HashMap<>();
// clear obsolete table items from map:
table.getItems().addListener((Change<? extends Person> c) -> {
if (c.wasRemoved()) {
c.getRemoved().forEach(checkedRows::remove);
}
});
checkColumn.setCellFactory(CheckBoxTableCell.forTableColumn(i ->
checkedRows.computeIfAbsent(table.getItems().get(i), p -> new SimpleBooleanProperty())));
CheckBox checkAll = new CheckBox();
checkAll.setOnAction(e -> {
if (checkAll.isSelected()) {
table.getItems().forEach(p ->
checkedRows.computeIfAbsent(p, person -> new SimpleBooleanProperty()).set(true));
} else{
checkedRows.values().stream().forEach(checked -> checked.set(false));
}
});
checkColumn.setGraphic(checkAll);
checkColumn.setEditable(true);
table.getColumns().add(column("First Name", Person::firstNameProperty));
table.getColumns().add(column("Last Name", Person::lastNameProperty));
table.getColumns().add(column("Email", Person::emailProperty));
table.getItems().addAll(
new Person("Jacob", "Smith", "jacob.smith#example.com"),
new Person("Isabella", "Johnson", "isabella.johnson#example.com"),
new Person("Ethan", "Williams", "ethan.williams#example.com"),
new Person("Emma", "Jones", "emma.jones#example.com"),
new Person("Michael", "Brown", "michael.brown#example.com")
);
Button verify = new Button("Verify");
verify.setOnAction(evt -> {
checkedRows.entrySet().stream().filter(e -> e.getValue().get()).map(Entry::getKey)
.map(Person::getFirstName).forEach(System.out::println);
});
BorderPane root = new BorderPane(table);
BorderPane.setAlignment(verify, Pos.CENTER);
BorderPane.setMargin(verify, new Insets(5));
root.setBottom(verify);
primaryStage.setScene(new Scene(root, 600, 600));
primaryStage.show();
}
private static <S,T> TableColumn<S,T> column(String title, Function<S, ObservableValue<T>> property) {
TableColumn<S,T> col = new TableColumn<>(title);
col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
return col ;
}
public static void main(String[] args) {
launch(args);
}
}
with the usual Person model class:
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Person {
private final StringProperty firstName = new SimpleStringProperty();
private final StringProperty lastName = new SimpleStringProperty();
private final StringProperty email = new SimpleStringProperty();
public Person(String firstName, String lastName, String email) {
setFirstName(firstName);
setLastName(lastName);
setEmail(email);
}
public final StringProperty firstNameProperty() {
return this.firstName;
}
public final String getFirstName() {
return this.firstNameProperty().get();
}
public final void setFirstName(final String firstName) {
this.firstNameProperty().set(firstName);
}
public final StringProperty lastNameProperty() {
return this.lastName;
}
public final String getLastName() {
return this.lastNameProperty().get();
}
public final void setLastName(final String lastName) {
this.lastNameProperty().set(lastName);
}
public final StringProperty emailProperty() {
return this.email;
}
public final String getEmail() {
return this.emailProperty().get();
}
public final void setEmail(final String email) {
this.emailProperty().set(email);
}
}

how to create a table by using Nattable and add value into its column

I have to create a Nat Table with three column and add value in the column.please help me. thanks in Advance
hope this helps. For the details of the layer you can refer the http://www.vogella.com/tutorials/NatTable/article.html link which is quite apt.
import org.eclipse.nebula.widgets.nattable.NatTable;
import org.eclipse.nebula.widgets.nattable.config.AbstractRegistryConfiguration;
import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes;
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
import org.eclipse.nebula.widgets.nattable.config.DefaultNatTableStyleConfiguration;
import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry;
import org.eclipse.nebula.widgets.nattable.data.IDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultColumnHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultCornerDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DefaultRowHeaderDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.data.DummyBodyDataProvider;
import org.eclipse.nebula.widgets.nattable.grid.layer.ColumnHeaderLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.CornerLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.GridLayer;
import org.eclipse.nebula.widgets.nattable.grid.layer.RowHeaderLayer;
import org.eclipse.nebula.widgets.nattable.hideshow.ColumnHideShowLayer;
import org.eclipse.nebula.widgets.nattable.layer.AbstractLayerTransform;
import org.eclipse.nebula.widgets.nattable.layer.DataLayer;
import org.eclipse.nebula.widgets.nattable.layer.LabelStack;
import org.eclipse.nebula.widgets.nattable.layer.cell.IConfigLabelAccumulator;
import org.eclipse.nebula.widgets.nattable.reorder.ColumnReorderLayer;
import org.eclipse.nebula.widgets.nattable.selection.SelectionLayer;
import org.eclipse.nebula.widgets.nattable.style.CellStyleAttributes;
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;
import org.eclipse.nebula.widgets.nattable.style.Style;
import org.eclipse.nebula.widgets.nattable.util.GUIHelper;
import org.eclipse.nebula.widgets.nattable.viewport.ViewportLayer;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class Nat_explore {
private BodyLayerStack bodyLayer ;
private int statusColumn;
private int statusRejected;
private int statusInProgress;
private boolean check = false;
private NatTable nattable;
private String[] properties;
private static final String FOO_LABEL = "FOO";
private static final String CELL_LABEL = "Cell_LABEL";
public static void main(String[] args) {
new Nat_explore();
}
public Nat_explore() {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
properties = new String[3];
for(int i=0;i<properties.length;i++){
properties[i]="Column"+i;
}
//Setting the data layout layer
GridData gridData = new GridData();
gridData.heightHint = (int) 24;
gridData.widthHint = (int) 110;
IConfigRegistry configRegistry = new ConfigRegistry();
//Body Data Provider
IDataProvider dataProvider = new DataProvider(properties.length,55);
bodyLayer= new BodyLayerStack(dataProvider);
//datalayer.addConfiguration(new
//Column Data Provider
DefaultColumnHeaderDataProvider columnData = new DefaultColumnHeaderDataProvider(properties);
ColumnHeaderLayerStack columnlayer = new ColumnHeaderLayerStack(columnData);
//Row Data Provider
DefaultRowHeaderDataProvider rowdata = new DefaultRowHeaderDataProvider(dataProvider);
RowHeaderLayerStack rowlayer = new RowHeaderLayerStack(rowdata);
//Corner Data Provider
DefaultCornerDataProvider cornerdata = new DefaultCornerDataProvider(columnData, rowdata);
DataLayer cornerDataLayer = new DataLayer(cornerdata);
CornerLayer cornerLayer = new CornerLayer(cornerDataLayer, rowlayer, columnlayer);
GridLayer gridlayer = new GridLayer(bodyLayer, columnlayer, rowlayer, cornerLayer);
nattable = new NatTable(shell, gridlayer,false);
// Change for paint
IConfigLabelAccumulator cellLabelAccumulator = new IConfigLabelAccumulator() {
//#Override
public void accumulateConfigLabels(LabelStack configLabels,int columnPosition, int rowPosition) {
int columnIndex = bodyLayer.getColumnIndexByPosition(columnPosition);
int rowIndex = bodyLayer.getRowIndexByPosition(rowPosition);
if (columnIndex == 2 && rowIndex == 45) {
configLabels.addLabel(FOO_LABEL);
}
else if ((columnIndex == statusColumn) && (rowIndex == statusRejected) && (check ==true)) {
configLabels.addLabel(CELL_LABEL);
}
}
};
bodyLayer.setConfigLabelAccumulator(cellLabelAccumulator);
nattable.addConfiguration(new DefaultNatTableStyleConfiguration());
nattable.addConfiguration(new AbstractRegistryConfiguration() {
//#Override
public void configureRegistry(IConfigRegistry configRegistry) {
Style cellStyle = new Style();
cellStyle.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR,GUIHelper.COLOR_YELLOW);
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle,DisplayMode.NORMAL, FOO_LABEL);
cellStyle = new Style();
cellStyle.setAttributeValue(CellStyleAttributes.BACKGROUND_COLOR,GUIHelper.COLOR_RED);
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_STYLE, cellStyle,DisplayMode.NORMAL, CELL_LABEL);
}
});
nattable.setLayoutData(gridData);
nattable.setConfigRegistry(configRegistry);
nattable.configure();
shell.open();
while (!shell.isDisposed()) {
if(!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
public class DataProvider extends DummyBodyDataProvider{
public DataProvider(int columnCount, int rowCount) {
super(columnCount, rowCount);
}
#Override
public int getColumnCount() {
return properties.length;
}
#Override
public Object getDataValue(int columnIndex, int rowIndex) {
return new String("Column"+columnIndex+" Row"+rowIndex);
}
#Override
public int getRowCount() {
return 55;
}
#Override
public void setDataValue(int arg0, int arg1, Object arg2) {
}
}
public class BodyLayerStack extends AbstractLayerTransform {
private SelectionLayer selectionLayer;
public BodyLayerStack(IDataProvider dataProvider) {
DataLayer bodyDataLayer = new DataLayer(dataProvider);
ColumnReorderLayer columnReorderLayer = new ColumnReorderLayer(bodyDataLayer);
ColumnHideShowLayer columnHideShowLayer = new ColumnHideShowLayer(columnReorderLayer);
this.selectionLayer = new SelectionLayer(columnHideShowLayer);
ViewportLayer viewportLayer = new ViewportLayer(this.selectionLayer);
setUnderlyingLayer(viewportLayer);
}
public SelectionLayer getSelectionLayer() {
return this.selectionLayer;
}
}
public class ColumnHeaderLayerStack extends AbstractLayerTransform {
public ColumnHeaderLayerStack(IDataProvider dataProvider) {
DataLayer dataLayer = new DataLayer(dataProvider);
ColumnHeaderLayer colHeaderLayer = new ColumnHeaderLayer(dataLayer,Nat_explore.this.bodyLayer, Nat_explore.this.bodyLayer.getSelectionLayer());
setUnderlyingLayer(colHeaderLayer);
}
}
public class RowHeaderLayerStack extends AbstractLayerTransform {
public RowHeaderLayerStack(IDataProvider dataProvider) {
DataLayer dataLayer = new DataLayer(dataProvider, 50, 20);
RowHeaderLayer rowHeaderLayer = new RowHeaderLayer(dataLayer,Nat_explore.this.bodyLayer, Nat_explore.this.bodyLayer.getSelectionLayer());setUnderlyingLayer(rowHeaderLayer);
}
}
}

Javafx Combobox list index set to -1 when executing combobox.get(someobject)

I have a combo box that is populated with the following ObservableList:
final ObservableList<SimplePerson> persons = FXCollections.observableArrayList(
new SimplePerson("Jacob", 1),
new SimplePerson("Isabella", 2),
new SimplePerson("Ethan", 3),
new SimplePerson("Emma", 4),
new SimplePerson("Michael", 5)
);
The combobox's selected index will be set to -1, the combobox's textbox will be populated with "Michael", and the "Michael" item in the drop down list will not be selected when I run
setValue(new SimplePerson("Michael",5))
Here is some example code (SSCCE)
import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.property.IntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import javafx.util.Callback;
import javafx.scene.control.ListView;
import javafx.scene.control.ListCell;
public class ComboBoxDemo extends Application {
public class SimplePerson {
private StringProperty name;
private IntegerProperty id;
private String somethingElse;
public SimplePerson(String name, Integer id) {
setName(name);
setId(id);
}
public final void setName(String value) {
nameProperty().set(value);
}
public final void setId(Integer id) {
idProperty().set(id);
}
public String getName() {
return nameProperty().get();
}
public int getId() {
return idProperty().get();
}
public StringProperty nameProperty() {
if (name == null) {
name = new SimpleStringProperty(this, "name");
}
return name;
}
public IntegerProperty idProperty() {
if (id == null) {
id = new SimpleIntegerProperty(this, "id");
}
return id;
}
#Override
public String toString() {
return name.get();
}
}
final ObservableList<SimplePerson> persons = FXCollections.observableArrayList(
new SimplePerson("Jacob", 1),
new SimplePerson("Isabella", 2),
new SimplePerson("Ethan", 3),
new SimplePerson("Emma", 4),
new SimplePerson("Michael", 5)
);
#Override
public void start(Stage stage) throws Exception {
final ComboBox<SimplePerson> cb = new ComboBox<>();
final ComboBox<String> cb2 = new ComboBox<>();
cb.setItems(persons);
cb.setEditable(true);
cb.setConverter(new StringConverter<SimplePerson>() {
#Override
public String toString(SimplePerson p) {
if (p != null) {
System.out.println("Looking up toString " + p.getName());
return p.getName();
} else {
System.out.println("Looking up toString null");
return "";
}
}
#Override
public SimplePerson fromString(String name) {
if (cb.getValue() != null) {
((SimplePerson) cb.getValue()).setName(name);
cb.show();
System.out.println("Here I am" + ((SimplePerson) cb.getValue()).getName());
return (SimplePerson) cb.getValue();
}
System.out.println("Returning null");
return null;
}
});
stage.setScene(new Scene(cb));
stage.show();
cb.setCellFactory(new Callback<ListView<SimplePerson>, ListCell<SimplePerson>>() {
#Override
public ListCell<SimplePerson> call(ListView<SimplePerson> l) {
return new ListCell<SimplePerson>() {
#Override
protected void updateItem(SimplePerson item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
System.out.println("I'm null");
} else {
System.out.println("Go get them " + item.getName());
setText(item.getName());
}
}
};
}
});
cb.setValue(new SimplePerson("Michael", 5));
System.out.println(cb.getSelectionModel().getSelectedIndex());
System.out.println(cb.getValue().getName());
}
public static void main(String[] args) {
launch(args);
}
}
The drop down list will select the right item when the ObservableList contains Strings
ObservableList<String>
You are passing a new Object to setValue() into the ComboBox. The Michael that is displayed when the ComboBox pops up is not same as the Michael in the dropdown.
If you pass cb.setValue(new SimplePerson("xyz", 5)); then the ComboBox will show the initially selected item as xyz, where xyz is not in the List of Person.
To set the exact object, you need to fetch them from their original reference, which in your case is the ObservableList<SimplePerson> persons. To fetch Michael, we use its index :
cb.setValue(persons.get(4));

GWT RPC - Why the results from database are printed twice ?

I am writing a simple app to enter a user into database & display list of users using GWT RPC, Hibernate in Eclipse. The problem I am getting is that the list of users is printed twice.
Here is my code where I call insert user & display users list methods.
package rpctest.client;
import java.util.ArrayList;
import rpctest.shared.User;
import rpctest.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Rpctest implements EntryPoint {
final TextBox firstName = new TextBox();
final TextBox lastName = new TextBox();
final Button ans = new Button("Add User");
//final Label label1 = new Label("First Name");
//final Label label2 = new Label("Last Name");
private FlexTable userFlexTable = new FlexTable();
//final Label errorLabel = new Label();
private VerticalPanel mainpanel = new VerticalPanel();
private HorizontalPanel addpanel1 = new HorizontalPanel();
private HorizontalPanel addpanel2 = new HorizontalPanel();
private final RpctestServiceAsync callService = GWT
.create(RpctestService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
userFlexTable.setText(0, 0, "User ID");
userFlexTable.setText(0, 1, "First Name");
userFlexTable.setText(0, 2, "Second Name");
userFlexTable.setText(0, 3, "Remove");
//add input boxes to panel
addpanel1.add(firstName);
addpanel1.add(lastName);
firstName.setFocus(true);
//add input/result panels
mainpanel.add(userFlexTable);
mainpanel.add(addpanel1);
addpanel1.add(ans);
ans.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
addStock();
}
});
lastName.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
addStock();
}
}
});
RootPanel.get().add(mainpanel);
getUser();
}
private void addStock(){
String name1 = firstName.getValue();
// Stock code must be between 1 and 10 chars that are numbers, letters, or dots.
/*if (!name1.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + name1 + "' is not a valid name.");
firstName.selectAll();
return;
}*/
firstName.setValue("");
String name2 = lastName.getValue();
/*if (!name2.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + name1 + "' is not a valid name.");
lastName.selectAll();
return;
}*/
lastName.setValue("");
firstName.setFocus(true);
callService.addUser(name1,name2,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("check your inputs");
}
#Override
public void onSuccess(String result) {
// TODO Auto-generated method stub
// Add the user to the table.
// int row = userFlexTable.getRowCount();
// userFlexTable.setText(row, 1, result);
getUser();
}
});
}
private void getUser(){
callService.getUser(new AsyncCallback<User[]>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("Problem in database connection");
}
#Override
public void onSuccess(User[] result) {
// TODO Auto-generated method stub
for(int i = 0; i < result.length; i ++)
{
//String s = result[i].getFirstName();
int row = userFlexTable.getRowCount();
userFlexTable.setText(row, 0, result[i].getId().toString());
userFlexTable.setText(row, 1, result[i].getFirstName());
userFlexTable.setText(row, 2, result[i].getLastName());
}
}
});
}
}
Man did you notice that you are calling getUser twice if the entered Name is valid and the call to the service is successfull??
You have to remove one of them!
getUser is called on every new entry & all data is entered again into table.

gwt celltable not working with uibinder

I got the following code from http://robin.mytechtip.com/2010/11/17/gwt-celltable-example-using-asyncdataprovider/#comment-920. I am trying to get it to work with uibinder. The result is that all data is shown in the celltable and therefore the simplePager navigation is disabled.
package com.example.random.client.view;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import com.example.random.shared.Contact;
import com.google.gwt.cell.client.DateCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
public class HtmlBinder extends Composite {
private static HtmlBinderUiBinder uiBinder = GWT
.create(HtmlBinderUiBinder.class);
interface HtmlBinderUiBinder extends UiBinder<Widget, HtmlBinder> {
}
#SuppressWarnings("deprecation")
private static final List<Contact> CONTACTS = Arrays.asList(new Contact(
"John", new Date(80, 4, 12), "123 Abc Avenue"), new Contact("Joe",
new Date(85, 2, 22), "22 Lance Ln"), new Contact("Tom", new Date(
85, 3, 22), "33 Lance Ln"), new Contact("Jack",
new Date(85, 4, 22), "44 Lance Ln"), new Contact("Tim", new Date(
85, 5, 22), "55 Lance Ln"), new Contact("Mike",
new Date(85, 6, 22), "66 Lance Ln"), new Contact("George",
new Date(46, 6, 6), "77 Lance Ln"));
/**
* The main CellTable.
*/
#UiField(provided = true)
CellTable<Contact> cellTable;
/**
* The pager used to change the range of data.
*/
#UiField(provided = true)
SimplePager pager;
public HtmlBinder() {
pager = new SimplePager();
cellTable = new CellTable<Contact>(3);
initWidget(uiBinder.createAndBindUi(this));
setupCellTable();
setupSimplePager();
}
private void setupSimplePager() {
pager.setDisplay(cellTable);
}
private void setupCellTable() {
// Add a text column to show the name.
TextColumn<Contact> nameColumn = new TextColumn<Contact>() {
#Override
public String getValue(Contact object) {
return object.getName();
}
};
cellTable.addColumn(nameColumn, "Name");
// Add a date column to show the birthday.
DateCell dateCell = new DateCell();
Column<Contact, Date> dateColumn = new Column<Contact, Date>(dateCell) {
#Override
public Date getValue(Contact object) {
return object.getBirthday();
}
};
cellTable.addColumn(dateColumn, "Birthday");
// Add a text column to show the address.
TextColumn<Contact> addressColumn = new TextColumn<Contact>() {
#Override
public String getValue(Contact object) {
return object.getAddress();
}
};
cellTable.addColumn(addressColumn, "Address");
// Associate an async data provider to the table
// XXX: Use AsyncCallback in the method onRangeChanged
// to actaully get the data from the server side
AsyncDataProvider<Contact> provider = new AsyncDataProvider<Contact>() {
#Override
protected void onRangeChanged(HasData<Contact> display) {
int start = display.getVisibleRange().getStart();
int end = start + display.getVisibleRange().getLength();
end = end >= CONTACTS.size() ? CONTACTS.size() : end;
List<Contact> sub = CONTACTS.subList(start, end);
updateRowData(start, sub);
}
};
provider.addDataDisplay(cellTable);
provider.updateRowCount(CONTACTS.size(), true);
}
}
Entrypoint ...
public void onModuleLoad() {
RootLayoutPanel.get().add(new HtmlBinder());
}