问题
I am facing the same problem mentioned here SWT: Table lost selection . I am using ubuntu 12.04 NOT windows. Is there any way to highlight the selected row of a SWT table even after focus lost. I tried adding focus listener to the table and in focus lost I changed the selected item background colour and on focus gain resets the background colour. See the code.
@Override
public void focusLost(FocusEvent e) {
System.out.println("table focus los");
TableItem item = fileListTable
.getItem(fileListTable.getSelectionIndex());
prevSelItemBackground = item.getBackground();
item.setBackground(soureWindow.getSelectionBackground());//Some random colour
System.out.println(fileListTable.getSelectionIndex());
}
@Override
public void focusGained(FocusEvent e) {
System.out.println("table focus gain");
TableItem item = fileListTable
.getItem(fileListTable.getSelectionIndex());
item.setBackground(prevSelItemBackground);
System.out.println(fileListTable.getSelectionIndex());
}
But it is not working. Is there any other solution/workaround for this?
回答1:
The below snippet can be used:
this.fileListTable.addSelectionListener(new SelectionListener() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// Nothing to do
}
@Override
public void widgetSelected(SelectionEvent e) {
int selectionIndex = fileListTable.getSelectionIndex();
TableItem[] items = fileListTable.getItems();
TableItem newItem;
for (int i = 0; i < items.length; i++) {
String first = items[i].getText(0);
String second = items[i].getText(1);
String third = items[i].getText(2);
items[i].dispose();
newItem = new TableItem(fileListTable, SWT.NONE);
newItem.setText(new String[] { first, second, third });
if (i == selectionIndex) {
newItem.setForeground(soureWindow.getSelectionForeground());//Or Anyother color
newItem.setBackground(soureWindow.getSelectionBackground());//Or Anyother color
} else {
newItem.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));//Default foreground color
newItem.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));//Default background color
}
}
}
});
Its is working fine for me but not tested on larger data.
来源:https://stackoverflow.com/questions/17614209/highlighting-swt-table-row-on-focus-lost