Wednesday, February 6, 2008

How to easily add menus & actions to jface/swt viewers - adding a table row

Assume you created a nice new empty table to be filled by a user.
And let's say you created a first empty row with two columns.


List elements = new ArrayList();

TableViewer tViewer = new TableViewer(parent, SWT.MULTI);
table = tViewer.getTable();
table.setLayoutData(new GridData(GridData.FILL_BOTH));
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableLayout layout = new TableLayout();
layout.addColumnData(new ColumnWeightData(50, true));
layout.addColumnData(new ColumnWeightData(50, true));
table.setLayout(layout);
TableColumn dateColumn = new TableColumn(table, SWT.LEFT);
dateColumn.setText("DATE");
TableColumn dischargeColumn = new TableColumn(table, SWT.LEFT);
dischargeColumn.setText("DISCHARGE");
TableLabelProvider sLP = new TableLabelProvider(); // implement this yourself
tViewer.setLabelProvider(sLP);
tViewer.setContentProvider(new ArrayContentProvider());
// the empty row
elements.add(new String[]{"", ""});
// set the input
tViewer.setInput(elements);


what to do very quickly to add a new row?
After fiddling a bit around with listeners and such stuff, I decided to exploit the menus:


// add a popup for new rows
MenuManager popManager = new MenuManager();
IAction menuAction = new NewRowAction();
popManager.add(menuAction);
Menu menu = popManager.createContextMenu(table);
table.setMenu(menu);


And how easy is the creation of the action?
Like that:


private class NewRowAction extends Action {
public NewRowAction() {
super("Add a new row");
}
public void run() {
elements.add(new String[]{"", ""});
tViewer .refresh();
}
}


et voila', right-click on the table and tell it to add the new row.

No comments: