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;
}
});
Related
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.
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.
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.
i hava a CheckboxTableViewer which has 10 columns, and the table is filled from database,
and i have a button outside the table named as "Delete",
what i want to do is:-
when i select rows using check box (multiple selection also) and when i press the "delete" button , i want the selected rows should get deleted from the database, and the tableviewer shuold get refreshed.
am pasting my tableviewer code below:-
final CheckboxTableViewer dataTable = CheckboxTableViewer.newCheckList(TableComposite2, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.BORDER |SWT.DM_FILL_BACKGROUND|SWT.FULL_SELECTION);
dataTable .getTable().setHeaderVisible(true);
dataTable .getTable().setLinesVisible(true);
dataTable .setContentProvider(new ArrayContentProvider());
//Action Check box
TableColumn columnCHead=new TableColumn(dataTable .getTable(),SWT.NONE);
columnCHead.setText("Delete");
columnCHead.setWidth(50);
// setting column input
TableViewerColumn columnC=new TableViewerColumn(dataTable ,columnCHead);
columnC.setLabelProvider(new ColumnLabelProvider()
{
public String getText(Object Element)
{
return null;
}
});
TableColumn columnFS1Head=new TableColumn(dataTable .getTable(),SWT.NONE);
columnFS1Head.setText("SOURCE DIRECTORY");
columnFS1Head.setWidth(300);
TableViewerColumn columnFS1=new TableViewerColumn(dataTable ,columnFS1Head);
columnFS1.setLabelProvider(new ColumnLabelProvider()
{
public String getText(Object Element)
{
AgedFileMaster a=(AgedFileMaster)Element;
return a.getDIRECTORY_PATH();
}
enter code here});
......
and i have a button for delete operation,(outside the table),
when i press delete button, i want the selected rows to get deleted...
am beginner to SWT.
anyone please help......
Use addSelectionListener on your Button control to be notified when the button is pressed:
button.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent event)
{
// TODO handle delete here
}
});
You need to do two things to remove the data - first update your data model to remove the objects and secondly tell the table viewer that the model has changed.
You can do something like this:
dataTable.getTable().setRedraw(false); // Stop redraw during update
IStructuredSelection selection = (IStructuredSelection)dataTable.getSelection();
for (Iterator<?> iterator = selection.iterator(); iterator.hasNext(); )
{
Object selectedObject = iterator.next();
// TODO remove from data model array
// Tell table view the object has been removed
dataTable.remove(selectedObject);
}
dataTable.getTable().setRedraw(true); // Allow updates to be drawn
An alternative to calling dataTable.remove on each object is to call dataTable.refresh once at the end. There is also a variant of remove which accepts an array of objects.
TableViewerColumn actionsNameCol = new TableViewerColumn(viewer, column);
actionsNameCol.setLabelProvider(new ColumnLabelProvider(){
//make sure you dispose these buttons when viewer input changes
Map<Object, Button> buttons = new HashMap<Object, Button>();
#Override
public void update(ViewerCell cell) {
TableItem item = (TableItem) cell.getItem();
Button button;
if(buttons.containsKey(cell.getElement()))
{
button = buttons.get(cell.getElement());
}
else
{
button = new Button((Composite) cell.getViewerRow().getControl(),SWT.NONE);
button.setText("Remove");
buttons.put(cell.getElement(), button);
}
TableEditor editor = new TableEditor(item.getParent());
editor.grabHorizontal = true;
editor.grabVertical = true;
editor.setEditor(button , item, cell.getColumnIndex());
editor.layout();
}
});
Delete selected rows (multiple rows) from Table when button clicks (Database Connectivity)
//Java ArrayList class uses a dynamic array for storing the elements
List<String> id_list=new ArrayList<String>();
//Button Text:Selected Row Delete
Button btnNewButton = new Button(parent, SWT.NONE);
btnNewButton.setText("Selected Row Delete");
btnNewButton.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
TableItem[] item=table.getItems();
for(int i=0;i<table.getItemCount();i++)
{
if(item[i].getChecked()&&!item[i].getText(1).equals(""))
{
String id=item[i].getText(1);
id_list.add(id);//Add ID into List
}
}
for(int j=0;j<id_list.size();j++)
{
//class:Test
//Method:DeleteData(String ID) pass id to delete rows
// type cast object into string
Test.DeleteData((String) id_list.get(j));
}
}
});
btnNewButton.setImage(ResourceManager.getPluginImage("RCP_Demo", "icons/delete.png"));
btnNewButton.setBounds(18, 370, 68, 23);
Test.java
public class Test {
static Connection conn = null;
static PreparedStatement presta=null;
public static void DeleteData(String ID)
{
String url = "jdbc:sqlite:Demo.db";
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(url);
presta = conn.prepareStatement("delete from Student where sid=?");
presta.setString(1, ID);
presta.executeUpdate();
DisplayData();
}catch(Exception e)
{
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}//End DeleteData()
}//End Test class
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();
}
});