Java SWT: how to delete the selected row in a SWT table - swt

I have implemented one SWT table having a button widget in one column. On click of a button I am deleting the entire row. But I don't understand how to refresh/redraw/update the table.
Table processListTable;
TableItem tableItem;
Image deleteImage = Activator.getImageDescriptor("icons/trash.gif").createImage();
private void addRowInTable() {
tableItem = new TableItem(processListTable, SWT.FILL);
tableItem.setText(0, "value 1");
tableItem.setText(1, "value 2");
TableEditor editor = new TableEditor(processListTable);
final Button deleteButton = new Button(processListTable, SWT.PUSH | SWT.FILL);
deleteButton.pack();
editor.minimumWidth = deleteButtonButton.getSize().x;
editor.horizontalAlignment = SWT.CENTER;
editor.setEditor(deleteButtonButton, tableItem, 2);
deleteButtonButton.setImage(deleteImage);
deleteButtonButton.addListener(SWT.Selection, new SelectionListener(tableItem, checkButton));
}
class SelectionListener implements Listener {
TableItem item;
Button deleteButton;
public SelectionListener(TableItem item, Button deleteButton) {
this.item = item;
this.deleteButton = deleteButton;
}
public void handleEvent(Event event) {
this.deleteButton.dispose();
this.item.dispose();
}
}

Check SWT snippet remove selected items from Table.
Just call table.remove(int rowIdx); instead of item.dispose();

public void handleEvent(Event event) {
this.deleteButton.dispose();
this.trash.dispose();
this.item .dispose();
Table table = viewer.getTable();
table.getColumn(2).pack();
table.getColumn(2).setWidth(100);
}
This is the solution for refresh the SWT table.

Use the JFace TableViewer with a model class, delete the object from the model and refresh the TableViewer.

Related

Delete rows from Nattable

I want to implement a row deletion logic in a Nebula Nattable.
This is what I plan to do:
Add context menu to the Nattable which is described in http://blog.vogella.com/2015/02/03/nattable-context-menus-with-eclipse-menus/
Add an SWT Action to the menu which will implement the delete
my question is, which is the best way to accomplish this:
Should I delete the corresponding value from my data model and the table view is refreshed when I execute this.natview.refresh();?
OR
Should I get the rows from SelectionLayer and delete them (if so how do I do ?)?
OR
is there any default support for this function through IConfiguration?
In NatTable you would typically do the following:
Create a command for deleting a row
public class DeleteRowCommand extends AbstractRowCommand {
public DeleteRowCommand(ILayer layer, int rowPosition) {
super(layer, rowPosition);
}
protected DeleteRowCommand(DeleteRowCommand command) {
super(command);
}
#Override
public ILayerCommand cloneCommand() {
return new DeleteRowCommand(this);
}
}
Create a command handler for that command
public class DeleteRowCommandHandler<T> implements ILayerCommandHandler<DeleteRowCommand> {
private List<T> bodyData;
public DeleteRowCommandHandler(List<T> bodyData) {
this.bodyData = bodyData;
}
#Override
public Class<DeleteRowCommand> getCommandClass() {
return DeleteRowCommand.class;
}
#Override
public boolean doCommand(ILayer targetLayer, DeleteRowCommand command) {
//convert the transported position to the target layer
if (command.convertToTargetLayer(targetLayer)) {
//remove the element
this.bodyData.remove(command.getRowPosition());
//fire the event to refresh
targetLayer.fireLayerEvent(new RowDeleteEvent(targetLayer, command.getRowPosition()));
return true;
}
return false;
}
}
Register the command handler to the body DataLayer
bodyDataLayer.registerCommandHandler(
new DeleteRowCommandHandler<your type>(bodyDataProvider.getList()));
Add a menu item to your menu configuration that fires the command
new PopupMenuBuilder(natTable)
.withMenuItemProvider(new IMenuItemProvider() {
#Override
public void addMenuItem(NatTable natTable, Menu popupMenu) {
MenuItem deleteRow = new MenuItem(popupMenu, SWT.PUSH);
deleteRow.setText("Delete");
deleteRow.setEnabled(true);
deleteRow.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent event) {
int rowPosition = MenuItemProviders.getNatEventData(event).getRowPosition();
natTable.doCommand(new DeleteRowCommand(natTable, rowPosition));
}
});
}
})
.build();
Using this you don't need to call NatTable#refresh() because the command handler fires a RowDeleteEvent. I also don't suggest to call NatTable#refresh() in such a case, as it might change and refresh more than it should and would not update other states correctly, which is done correctly by firing the RowDeleteEvent.
Note that the shown example deletes the row for which the context menu is opened. If all selected rows should be deleted, you should create a command handler that knows the SelectionLayer and retrieve the selected rows as shown in the other answer.
In our application we do the following:
Get selected row objects:
SelectionLayer selectionLayer = body.getSelectionLayer();
int[] selectedRowPositions = selectionLayer.getFullySelectedRowPositions();
Vector<Your Model Objects> rowObjectsToRemove = new Vector<Your Model Objects>();
for (int rowPosition : selectedRowPositions) {
int rowIndex = selectionLayer.getRowIndexByPosition(rowPosition);
rowObjectsToRemove .add(listDataProvider.getRowObject(rowIndex));
}
Remove them from the data provider
call natTable.refresh()

GWT CellTable SelectionModel can not deselect item after editing

Hello I have a Contact class with informations which i show in a CellTable.
The CellTable has a DataListProvider, MultiSelectionModel and KeyProvider
which checks the id of the Contact.
DataListProvider and CellTable have the same KeyProvider.
if i only select/deselect the items in the CellTable and show them in a TextBox ists working fine. But the when i change the value of the Contact item in the TextBox(Contact instance) and try to deselect the item the selectionmodel says its still selected?
I tried with clear() but its still selected!
GWT 2.5 / FireFox
ProvidesKey<Contact> keyProvider = new ProvidesKey<Contact>(){
#Override
public Object getKey(Contact item) {
return item.getIdContact();
}
};
public MyCellTable(boolean canLoad, Integer pagesize, ProvidesKey<T> keyProvider) {
super(-1, resource, keyProvider);
selectionModel = new MultiSelectionModel<T>();
selectionModel .addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
#Override
public void onSelectionChange(SelectionChangeEvent event) {
selectionChange();
}
});
dataProvider = new ListDataProvider<T>(keyProvider);
dataProvider.addDataDisplay(this);
}
in the selection event i call
protected void selectionChange(){
Contact c = grid.getGrid().getSelectedItem();
if(c != null){
cpForm.enable();
cpForm.clear();
form.bind(c); // Formular which updates the selected instance
cpForm.add(form);
}else{
cpForm.disable(noseletionText);
}
}
i have no ValueUpdater
when i select an item i generate a formular and if i change something i call:
#Override
public void save() {
super.save();
ContactServiceStore.get().updateContact(manager.getBean(),
new MyAsyncCallback<Void>() {
#Override
public void onSuccess(Void result) {
onchange();
}
});
}
i if call the method without changes on the contact its still working and i can deselect but when i change the name or something else i cant select other items or deselect the current item!
You're not actually using your ProvidesKeys in your MultiSelectionModel. You need to create your MultiSelectionModel like so:
MultiSelectionModel<T> selectionModel = new MultiSelectionModel<T>(keyProvider);
If you don't supply the MultiSelectionModel with a ProvidesKey it will use the actual object as a key.
Make sure you also add the MultiSelectionModel to the table:
cellTable.setSelectionModel(selectionModel);
The reason selectionModel.clear() wasn't working was because selectionModel was not set to the table.

GWT CellTable Custom Selection Model

I need a 'custom selection model' for GWT CellTable. One of the columns in CellTable is a Checkbox column.
Basic rquirements (both work in solution below):
- Row click (not on checkbox), selects that row and un-selects all other rows.
- Checkbox selection should select/un-select that row only.
Following is the code I am using, but its very very slow. Any guidance would be appreciated.
final SelectionModel<T> selectionModel = new MultiSelectionModel<T>();
dataTable.setSelectionModel(selectionModel,
DefaultSelectionEventManager.createCustomManager(
new DefaultSelectionEventManager.CheckboxEventTranslator<T>() {
#Override
public SelectAction translateSelectionEvent(CellPreviewEvent<T> event) {
SelectAction action = super.translateSelectionEvent(event);
if (action.equals(SelectAction.IGNORE)) {
selectionModel.clear();
return SelectAction.TOGGLE;
}
return action;
}
}
)
);
Following is the code snipped for CheckColumn callback.
Column<T, Boolean> checkColumn = new Column<T, Boolean>(
new CheckboxCell(true, false))
{
#Override
public Boolean getValue(T t)
{
// Get the value from the selection model.
return selectionModel.isSelected(t);
}
};
I have put in a KeyProvider for the CellTable and its not slow anymore. :)
ProvidesKey<T> keyProvider = new ProvidesKey<T>() {
public Object getKey(T t) {
return tip == null? null : tip.getId();
}
};
dataTable = new CellTable<T>(PAGE_SIZE, keyProvider);
You could just whitelist your checkbox
int checkboxColumn = 0;
DefaultSelectionEventManager.createCustomManager(new DefaultSelectionEventManager
.WhitelistEventTranslator(checkboxColumn));

Setting ListGrid selection in SmartGWT with method "selectRecords(Record record)"

I'm trying to set the selected records of a ListGrid table object in SmartGWT using records, but I can't find any way of doing it. I want to select with record, not index. I want to use selectRecord(Record record) method.
As an example;
public void onModuleLoad()
{
VLayout main = new VLayout();
final ListGrid grid = new ListGrid();
grid.setHeight(500);
grid.setWidth(400);
grid.setFields(new ListGridField("name", "Name"));
grid.setData(createRecords());
final IButton button = new IButton("Select some");
button.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event)
{
grid.selectRecord(createRecord("orange"));
}
});
main.addMember(grid);
main.addMember(button);
RootPanel.get().add(main);
}
private ListGridRecord[] createRecords()
{
return new ListGridRecord[]{
createRecord("monkey"),
createRecord("banana"),
createRecord("orange"),
createRecord("sun")
};
}
private ListGridRecord createRecord(String name)
{
ListGridRecord record = new ListGridRecord();
record.setAttribute("name", name);
return record;
}
In this case I want to select orange, But this code select anything.
Is it posible? If possible how?
Thanks in advance.
Found this solution;
selectRecord(grid.getRecordList().find("name", "orange"));
There's a problem with your code:
When you write
grid.selectRecord(record);
it goes to search the same record instance that the grid has. If both instances of record are equal, only then & then it selects the record. Otherwise nothing happens as you're facing right now. Here what you need to do is:
ListGridRecord[] records = countryGrid.getRecords();
int i;
for (i = 0; i < records.length; i++)
{
if (records[i].getAttribute("name").equalsIgnoreCase("orange"))
{
break;
}
}
countryGrid.selectRecord(i);

Setting ListGrid selection in SmartGWT

I'm trying to set the selected records of a ListGrid table object in SmartGWT, but I can't find any way of doing it. I know there's a getSelectedRecords() function, but no matching setSelectedRecords(). I tried to see if set/getSelectedState() would work, but GWT complains about needing a primary key and a DataSource object. Is there any way to set the selection of a ListGrid?
For this you can use one of the selectRecords() methods, like so:
public void onModuleLoad()
{
VLayout main = new VLayout();
final ListGrid grid = new ListGrid();
grid.setHeight(500);
grid.setWidth(400);
grid.setFields(new ListGridField("name", "Name"));
grid.setData(createRecords());
final IButton button = new IButton("Select some");
button.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event)
{
grid.selectRecords(new int[]{2, 3}); //This will select index 2 and 3
}
});
main.addMember(grid);
main.addMember(button);
RootPanel.get().add(main);
}
private ListGridRecord[] createRecords()
{
return new ListGridRecord[]{
createRecord("monkey"),
createRecord("banana"),
createRecord("orange"),
createRecord("sun")
};
}
private ListGridRecord createRecord(String name)
{
ListGridRecord record = new ListGridRecord();
record.setAttribute("name", name);
return record;
}