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));
TableLayout layout = new TableLayout();
layout.addColumnData(new ColumnWeightData(50, true));
layout.addColumnData(new ColumnWeightData(50, true));
TableColumn dateColumn = new TableColumn(table, SWT.LEFT);
TableColumn dischargeColumn = new TableColumn(table, SWT.LEFT);
TableLabelProvider sLP = new TableLabelProvider(); // implement this yourself
tViewer.setContentProvider(new ArrayContentProvider());
// the empty row
elements.add(new String[]{"", ""});
// set the input

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();
Menu menu = popManager.createContextMenu(table);

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: