How to get values of grid in GXT? - java

List<ColumnConfig<Vo, ?>> l = new ArrayList<ColumnConfig<Vo, ?>>();
l.add(numColumn);
l.add(subjectColumn);
l.add(nameColumn);
l.add(dateColumn);
ColumnModel<Vo> cm = new ColumnModel<Vo>(l);
Grid<Vo> grid = new Grid<Vo>(store, cm) {
#Override
protected void onAfterFirstAttach() {
super.onAfterFirstAttach();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
#Override
public void execute() {
loader.load();
}
});
}
};
grid.addCellClickHandler(new CellClickHandler() {
#Override
public void onCellClick(CellClickEvent event) {
// TODO Auto-generated method stub
contentPanel.clear();
contentPanel.add(readPanel(contentPanel));
}
});`
When I click on cell, I want to get the data in the cell corresponding.
The current state,
When you click on of the cell, switch to a different view of the structure.
And I succeeded to connect to the database.
However, I want to get the data of cell or row.
How to get values of grid in GXT?
(example Site:http://www.sencha.com/examples/#ExamplePlace:paginggrid)

GXT Grid works with data stores, more precisely it is a ListStore I think. So that, to get Values of the grid either use that store by grid.getStore(), and after that you basically have a collection of the objects in your grid (grid.getStore().getAll() return List), or you can use Grid's SelectionModel to deal with the grid selected item like this:
grid.getSelectionModel().addSelectionChangedHandler(new SelectionChangedHandler<Vo>() {
#Override
public void onSelectionChanged(SelectionChangedEvent<Vo> event) {
if (grid.getSelectionModel().getSelectedItem() != null) {
// Do whatever you want
} else {
}
}
});
I hope it will help.

If you want to get the value of a single cell you can try this inside the cellClickHandler :-
ListGridRecord record = event.getRecord();
int colNum = event.getColNum();
String fieldName=grid.getFieldName(colNum);
String cellValue=record.getAttribute(fieldName);
cellValue will have the desired value.

Related

Check/Uncheck CheckboxCell, onclick of a row - GWT

I have a cell table with the first column as checkboxes. My checkboxes have to be checked or unchecked when there is any single click event on the entire row. This is the following code for creating a MultiSelectionModel, creating CheckboxCell and creating a column for cell table.
MultiSelectionModel<Object> selectionModel = new MultiSelectionModel<>();
table.setSelectionModel(selectionModel);
CheckboxCell selectedCell = new CheckboxCell();
Column<Object,Boolean> selectedCol = new Column<Object, Boolean>(selectedCell){
#Override
public Boolean getValue(Object object) {
return object.isSelected();
}
};
table.addColumn(selectedCol);
//Single Click Event to Enable/Disable checkbox.
table.addDomHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Set<Object> selectedItems = selectionModel.getSelectedSet();
for (Object s : selectedItems) {
Window.alert(String.valueOf(s));
selectionModel.setSelected(s, true);
}
}
}, ClickEvent.getType());
I tried to mark a row as checked using "selectionModel.setSelected(s, true)". But it isn’t working, when I clicked on row, the corresponding checkbox is not being checked.
My question is how do I enable/disable checkboxes onclick of an entire row. Is my approach correct. Or Is there any other way to perform this action in GWT.
You are very close to the working solution.
In the selectedCell you should return the value depending on selectionModel:
return selectionModel.isSelected(object);
This way you are using default multi selection model that selects rows by clicking on them. And the checkbox value comes from the selection model. That's it.
See the working example below:
CellTable<String> table = new CellTable<String>();
final MultiSelectionModel<String> selectionModel = new MultiSelectionModel<>();
table.setSelectionModel(selectionModel);
CheckboxCell selectedCell = new CheckboxCell();
Column<String, Boolean> selectedCol = new Column<String, Boolean>(selectedCell) {
#Override
public Boolean getValue(String object) {
// return object.isSelected();
return selectionModel.isSelected(object);
}
};
table.addColumn(selectedCol);
table.addColumn(new TextColumn<String>() {
#Override
public String getValue(String object) {
return object;
}
});
List<String> values = new ArrayList<>();
for(int i = 0; i < 10; i++)
values.add("Line " + (i + 1));
table.setRowData(values);
You can use standard Ctrl and Shift keys to control selection.

How to set a label to row header cell based on row object condition NatTable

If a user makes a change in the data I want to be able to mark an indication in the row header cell of that row.
I tried a few things but was not successful.
I know that I should set a label to the cell and then decorate the cell with the icon.
I just don't know how to set a label based on the row object to the row header cell. Please help.
natTable.addConfiguration(new AbstractRegistryConfiguration() {
#Override
public void configureRegistry(IConfigRegistry configRegistry) {
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER,
new CellPainterDecorator(new ImagePainter() {
#Override
protected Image getImage(ILayerCell cell, IConfigRegistry configRegistry) {
Person obj = bodyLayerStack.getFilterList().get(cell.getRowIndex());
if (obj.isDirty() {
return dirtyImage;
} else {
return null;
}
}
}, CellEdgeEnum.LEFT, new TextPainter()), DisplayMode.NORMAL, DIRTY_CELL_LABEL);
}
});
How do I set this "DIRTY_CELL_LABEL" label to the row header cell of a particular row (not all rows).
I don't know how to accommodate my conditions in the CellOverrideLabelAccumulator.
You need to implement a custom IConfigLabelAccumulator as explained in our documentation https://www.eclipse.org/nattable/documentation.php?page=styling or the Getting started tutorial https://www.vogella.com/tutorials/NatTable/article.html or even in some posts here on stackoverflow if you search for it, e.g. Adding colors to row in nattable based on condition
For the lazy, here is some code that could be easily added to the NatTable examples. It works with the married property instead of a dirty property that is not available in the NatTable examples:
register an IColumnLabelAccumulator to the row header layer
RowHeaderLayer rowHeaderLayer =
new RowHeaderLayer(rowHeaderDataLayer, bodyLayer, bodyLayer.getSelectionLayer());
rowHeaderLayer.setConfigLabelAccumulator(new IConfigLabelAccumulator() {
#Override
public void accumulateConfigLabels(LabelStack configLabels, int columnPosition, int rowPosition) {
Person person = bodyLayer.getBodyDataProvider().getRowObject(rowPosition);
if (person.isMarried()) {
configLabels.addLabel("MARRIED");
}
}
});
Register the styling
natTable.addConfiguration(new AbstractRegistryConfiguration() {
#Override
public void configureRegistry(IConfigRegistry configRegistry) {
configRegistry.registerConfigAttribute(CellConfigAttributes.CELL_PAINTER,
new CellPainterDecorator(
new TextPainter(),
CellEdgeEnum.LEFT,
new ImagePainter() {
#Override
protected Image getImage(ILayerCell cell, IConfigRegistry configRegistry) {
return image;
}
}),
DisplayMode.NORMAL,
"MARRIED");
}
});
Note that an additional check in the ImagePainter is not needed as the label is only applied to cells with that state.

JComboBox Selection Change

everyone i am quite new to Java GUI, i am having an issue with a JComboBox , where it is firing when i removeAllItems from a combo box to refresh it, this is an issue because i am getting the selected items Details and populating a textboxes with them so as it is firing at that point i am getting a Null Pointer.
Is there any simple(ish) way to have method on the ComboBox that is called when the selected item is changed not just when the combo box contents is changed?
Code
comboBox current method
private void customerComboActionPerformed(java.awt.event.ActionEvent evt) {
setDetails();
}
Method for setting the Items in the combo Box
public void setCustomers()
{
customerCombo.removeAllItems();
for (Customer curr : Main.getNewCustomerList().getCustomers())
{
customerCombo.addItem(curr);
}
}
method for setting the details
public void setDetails()
{
Customer selected = (Customer) customerCombo.getSelectedItem();
forenameText.setText(selected.getForename());
surnameText.setText(selected.getSurname());
costperkgText.setText(String.valueOf(selected.getDeliveryCost()));
line1Text.setText(String.valueOf(selected.getColAddress().getAddressLine1()));
line2Text.setText(String.valueOf(selected.getColAddress().getAddressLine2()));
cityText.setText(String.valueOf(selected.getColAddress().getCity()));
postcodeText.setText(String.valueOf(selected.getColAddress().getPostcode()));
}
You are not accounting for the case where there is no selection.
public void setDetails()
{
Customer selected = (Customer) customerCombo.getSelectedItem();
if (selected != null)
{
// there is a selection so use it
}
else
{
// for example, clear the text boxes
}
}
We would also expect that changing the contents of the combo box might change its selection so we shouldn't ignore it.
I like to set a flag. The key is making sure the flag doesn't get stuck to false.
private volatile boolean fire = true;
public void setItems(Object[] items) {
try {
fire = false; // Don't fire updates
updateItems(items);
} finally {
fire = true; // always reset no matter what!
}
}
private JComboBox create() {
JComboBox cb = new JComboBox();
cb.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
if(fire) {
notifyListeners();
}
}
});
}
You have to make sure this isn't being called by multiple threads, but since Swing isn't thread safe this should be happening anyway.

GXT checkbox in grid

I need to update the store when the checkbox in the grid cell changed its state: to add or to remove the value from store. how to handle this event?
BTW, I create the checkbox in grid in this way:
column = new ColumnConfig();
column.setId("accepted");
column.setHeader("Accepted");
column.setWidth(55);
UPD2: Now I do the following:
create checkboxes as firstly decided:
CheckColumnConfig checkColumn = new CheckColumnConfig("accepted", "", 55);
CellEditor checkBoxEditor = new CellEditor(new CheckBox());
checkBoxEditor.setToolTip("If you click here server will consider this rule checking your messages");
checkColumn.setEditor(checkBoxEditor);
checkColumn.setHeader("apply");
configs.add(checkColumn);
than handle events in the grid like this:
UPD3:
grid.addListener(Events.CellMouseUp, new Listener<GridEvent>() {
#Override
public void handleEvent(GridEvent be) {
PropertyItem item;
if (grid.getStore().getAt(be.getRowIndex()).isAccepted()){
item = new PropertyItem(val1, val2, val3, true);
} else {
item = new PropertyItem(val1, val2, val3, false);
}
store.update(item);
store.commitChanges();
saveProperties(store, customerId, toRemove);
}
});
this is the right way.
According to the docs found here, you can add a listener to the CellEditor's Complete event. In the Complete event Listener, perform whatever activity you need to accomplish.
Update:
Try the following
column.setRenderer(new GridCellRenderer() {
#Override
public Object render(ModelData model, String property, ColumnData config, int rowIndex, int colIndex, final ListStore store, Grid grid) {
CheckBox box = new CheckBox();
box.addListener(Events.Change, new Listener<FieldEvent>() {
#Override
public void handleEvent(FieldEvent be) {
st.commitChanges();
saveProperties(st, customerId, toRemove);
// I'm not sure what saveProperties is, but see if this works now.
// this event should DEFINITELY be fired when the checkbox is clicked
// so if it doesn't work, try changing how you do your code here
// maybe by doing model.set(property, (Boolean) be.getValue()); or something
}
});
return box;
}
});

Moving Item in a table SWT/RCP

I have a problem with moving cell in a Table.
Have someone an idea how to move rows in an SWT Table? I want to change the order by user
interaction and I din't need to sort the entries.
I would like to achieve this in moving a selected row up or down by buttonklick or with moving a table items by drag and drop.
I am using eclips 3.6 and java 1.6
This is what I try with Drag and Drop but not working:
Transfer[] types = new Transfer[] { LocalSelectionTransfer.getTransfer()};
DragSource source = new DragSource(table, DND.DROP_MOVE );
source.setTransfer(types);
source.addDragListener(new DragSourceAdapter() {
public void dragSetData(DragSourceEvent event) {
// Get the selected items in the drag source
DragSource ds = (DragSource) event.widget;
Table table = (Table) ds.getControl();
TableItem[] selection = table.getSelection();
System.out.println(" drag "+ selection[0].getText());
}
});
DropTarget target = new DropTarget(table, DND.DROP_MOVE | DND.DROP_DEFAULT);
target.setTransfer(types);
TableViewer tb = new TableViewer(table);
tb.addDropSupport(DND.DROP_MOVE, types, new ViewerDropAdapter(viewer) {
#Override
public boolean validateDrop(Object target, int operation,
TransferData transferType) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean performDrop(Object data) {
// TODO Auto-generated method stub
return false;
}
});
The Item that I would like to move have more then a Column.
The error that I became is :
org.eclipse.swt.SWTError: Cannot initialize Drop
When I will be informed in which new Item (the index in Table) is the item moved it will be sufficient then I can change the List of my objects and redrew the table.
Any idea how to slove this problem?.
Regards,
Haythem
I think you need to add a dragSupport to the table viewer before adding a dropSupport. You don't need to use a DragSource :
TableViewer viewer = new TableViewer(table);
Transfer[] types = new Transfer[] { PluginTransfer.getInstance() };
viewer.addDragSupport(DND.DROP_MOVE, types, new DragSourceAdapter() {
#Override
public void dragSetData(DragSourceEvent event) {
// Get the selected items in the drag source
DragSource ds = (DragSource) event.widget;
Table table = (Table) ds.getControl();
TableItem[] selection = table.getSelection();
System.out.println(" drag " + selection[0].getText());
}
});
viewer.addDropSupport(DND.DROP_MOVE, types, new ViewerDropAdapter(viewer) {
#Override
public boolean validateDrop(Object target, int operation, TransferData transferType) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean performDrop(Object data) {
// TODO Auto-generated method stub
return false;
}
});
I have realized something like that, I am not sure however if I got your question right. Generally you have to modify your model and store the information of the index of the element in your model too. The list is then presented in the right order by applying a Comparator. The modification of the model is then handled by the respective Drag/Drop implementation. In this way you can realize the re-arranging of rows and the correct visualisation to the user.
Is this what you meant?
here i have a simple code to swapping/moving row in RCP. i using a button UP and down to swapping the row of table Viewer.
I added a selection listener on my button.
take the selected item index in the table.
save the original input of table viewer in a list.
stored the selected item of table in temp variable.
then remove from the list.
add temp variable into the list with index(+1 for down and -1 for up)
example:-
button.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
int selectionIndex = TableViewer.getTable().getSelectionIndex();
EObjectContainmentEList<Object> input = (EObjectContainmentEList<Object>) TableViewer.getInput();
Attribute basicGet = input.basicGet(selectionIndex);
input.remove(selectionIndex);
input.add(selectionIndex-1, basicGet);
TableViewer.setInput(input);
TableViewer.refresh();
}
});

Categories

Resources