gwt celltable not working with uibinder - gwt

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

Related

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

GWT CellList with dynamic DataProvider

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

Adding JCheckBox to JTable using Netbeans

I have a JTable in my JDialog which I populate myself in another method. Here is my code and I want the second null in my Object array to be a JCheckBox. I have been scowering the internet and saw someone say I need to override a method in the tablerenderer or something like that and I got confused on how to do it. Anyway here is the code
package privatelessontrackernetbeans;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TreeMap;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Brent C
*/
public class WeeklyLessonsReductionGUI extends javax.swing.JDialog {
/**
* Creates new form WeeklyLessonsReductionGUI
* #param parent
* #param modal
*/
public WeeklyLessonsReductionGUI(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
postInitComponents();
}
private void postInitComponents() {
ImageIcon icon = new ImageIcon(PSLTrackerInfo.file + "ymcaLogo.png");
setIconImage(icon.getImage());
//Table for students that need more lessons
DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
dtm.setRowCount(0);
//Center the Titles
DefaultTableCellRenderer centerRenderer = (DefaultTableCellRenderer)
jTable1.getTableHeader().getDefaultRenderer();
centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
//Center the Cells
jTable1.setDefaultRenderer(Object.class, centerRenderer);
TreeMap<Instructor, ArrayList<Student>> theList =
PSLTrackerInfo.theList_getMap();
for (Instructor key : theList.keySet()) {
ArrayList<Student> students = theList.get(key);
boolean listed = false;
for (Student values : students) {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, Calendar.MONDAY);
c.set(Calendar.WEEK_OF_YEAR, values.getLastUpdateWeek());
c.set(Calendar.YEAR, values.getLastUpdateYear());
DateFormat df = new SimpleDateFormat("MMMM dd, yyyy");
Date date = c.getTime();
String s = df.format(date);
if (listed) {
Object[] data = new Object[]{null,
values.getName(), s, null, null, null};
dtm.addRow(data);
} else {
Object[] data = new Object[]{values.getInstructor(),
values.getName(), s, null, null, null};
dtm.addRow(data);
listed = true;
}
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Lessons Update");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Instructor", "Student", "Last Update", "Lesson Date", "Lesson Complete", "Unscheduled Lessons"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, true, true
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
jButton1.setText("Update");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 829, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(375, 375, 375))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
No need for a custom renderer, just override the getColumnClass() method of the DefaultTableModel making the column with the boolean a Boolean object.
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class CheckBoxTable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Object[][] data
= {{"false", false},
{"true", true}};
String[] cols = {"String", "Boolean"};
DefaultTableModel model = new DefaultTableModel(data, cols) {
#Override
public Class<?> getColumnClass(int column) {
if (column == 1) {
return Boolean.class;
} else {
return String.class;
}
}
};
JTable table = new JTable(model);
JOptionPane.showMessageDialog(null, new JScrollPane(table));
}
});
}
}
why you just don't do a "new JCheckBox()" instead of the second null??

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 createing date object from string?

I'm using a motionchart in a gwt appliation. My question is how to create a Date object from a string? Following is my code:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.visualization.client.AbstractDataTable;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.visualizations.LineChart;
import com.google.gwt.visualization.client.visualizations.MotionChart;
import com.google.gwt.visualization.client.visualizations.MotionChart.Options;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import component.client.SQLRunner;
import component.client.SQLRunnerAsync;
public class DashboardWidget
{
private HorizontalPanel containerPanel=null;
private DataTable data=null;
public DashboardWidget()
{
containerPanel = new HorizontalPanel();
}
public HorizontalPanel getContainerPanel()
{
SQLRunnerAsync service = (SQLRunnerAsync) GWT.create(SQLRunner.class);
AsyncCallback<ArrayList<String[]>> callback = new AsyncCallback<ArrayList<String[]>>()
{
#Override
public void onFailure(Throwable caught)
{
}
#Override
public void onSuccess(final ArrayList<String[]> result)
{
Runnable onLoadCallback = new Runnable()
{
public void run()
{
DataTable data = DataTable.create();
data.addColumn(ColumnType.STRING, " Name");
data.addColumn(ColumnType.DATE, "Date");
data.addColumn(ColumnType.NUMBER, "Count");
data.addColumn(ColumnType.NUMBER, "Something");
data.addColumn(ColumnType.NUMBER, "Something Else");
data.addRows(result.size());
#**SuppressWarnings("deprecation")
Date date = new Date(1888,06,01);
DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy,MM,dd");**
for(int i=0;i<result.size();i++)
{
String[] temp = result.get(i);
String name=temp[0];//name
String count= temp[2];
String something=temp[3];
String seomthingElse=temp[5];
data.setValue(i, 0, name);//NAME
data.setValue(i, 1, date);//date
data.setValue(i, 2, Integer.parseInt(count));//eloc
data.setValue(i, 3, Integer.parseInt(something));//warning
data.setValue(i, 4, Integer.parseInt(somethingeElse));//static (open) warning
}
Options options = Options.create();
options.setWidth(1000);
options.setHeight(1000);
MotionChart chart = new MotionChart(data, options);
containerPanel.add(chart);
}
};
VisualizationUtils.loadVisualizationApi(onLoadCallback, MotionChart.PACKAGE);
}
};
service.getDataFromDatabase("","","","", callback);
return containerPanel;
}
}
So How Do I create a date object from String for a GWT application?
Can you not use the DateTimeFormat object? Something like this:
Date parsed = fmt.parse(text);