SWT: Table with copy/paste functions
This maybe a really silly question but I just could not find the answer anywhere, is there any way for the user to be able to highlight rows in an SWT Table and either ctrl+c or right-click+c to copy the values?
I would specifically like to be able to copy into an excel sheet.
This is how I create the table,
Table aTable = new Table(parent, SWT.SINGLE | SWT.BORDER
| SWT.FULL_SELECTION);
aTable.setHeaderVisible(true);
aTable开发者_开发知识库.setLinesVisible(true);
aTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
I have seen information about this using a JTable but nothing with an SWT. If JTable is my only option, then what would be the dis/advantages of using either?
You can easily code it.
Add a key listener to your table and listen for Ctrl+C keys. When Ctrl+C is hit, get the selection from the table, extract text from each of the TableItems and form a tab-separated-fields/newline-separated-rows String containing your data. Then just put it into clipboard (see org.eclipse.swt.dnd.Clipboard#setContents
, use TextTransfer data type).
That is it - your result will be pasteable into Excel.
The accepted answer is good, but since developers prefer code snippets over text I'd answer the question this way:
aTable.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.stateMask == SWT.CTRL && (e.keyCode == 'c' || e.keyCode == 'C')) {
Clipboard clipboard = new Clipboard(Display.getDefault());
clipboard.setContents(new Object[] { getTextFromSelectedRows() }, new Transfer[] { TextTransfer.getInstance() });
clipboard.dispose();
}
}
});
Then just implement a getTextFromSelectedRows()
-Method that - based on the table selection - returns the String
that should be added to the clipboard.
精彩评论