Moving Item in a table SWT/RCP - java

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

Related

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.

How to get values of grid in GXT?

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.

how to delete selected rows (multiple rows) from CheckboxTableViewer when button clicks? (table is connected to oracle database)

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

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

Show TableViewer not in line, but in matrix order

I use the TableViewer to show informations in a table. The user can select one of the shown options by selecting one line of the table.
I want to create a table in matrix form, in which the user can not only select the line. It should be possible to select every item of the table, like row 2 column 3. For every item selection an action is called to handle this item as it is in the TableViewer.
As far as i now, i can add CellModifier and CellEditors to the line of Columns of the table, but the reference for the action is always the line object and not the selected TableItem.
Does somebody have an example how to create such a matrix inside a Composite?
I can create it by setting a GridLayout and adding the components in a for-loop, but than i get issues, when i want to redraw the Composite with new childrens. The TableViewer does already have this handling, so i dont want to implement it again.
I had the same problem a while ago and the only way I found to solve it was to register a mouse listener on the SWT table widget associated to the table viewer.
MouseListener columnSelectionMouseListener = new ColumnSelectionMouseListener();
getViewer().getTable().addMouseListener(columnSelectionMouseListener);
public class ColumnSelectionMouseListener implements MouseListener {
private TableColumn selectedColumn;
#Override
public void mouseDoubleClick(MouseEvent e) {
// Nothing to do here
}
#Override
public void mouseDown(MouseEvent e) {
table = (Table) e.widget;
TableItem item = table.getItem(new Point(e.x, e.y));
for (int i = 0; i < table.getColumnCount(); i++) {
TableColumn column = table.getColumn(i);
Rectangle bounds = item.getBounds(i);
if (bounds.contains(e.x, e.y)) {
selectedColumn = column;
}
}
}
#Override
public void mouseUp(MouseEvent e) {
// Nothing to do here
}
public TableColumn getSelectedField() {
return selectedColumn;
}
}
Then, for example in the viewer's selection listener, you can ask to the mouse listener which column was selected when the mouse has been pressed and combine that with the selected line coming from the viewer's selection to perform the appropriate action.
Hope this can help.
Manu
Maybe the following JFace snippet will help:
Snippet058CellNavigationIn34
Ingo

Categories

Resources