嚴格基於此table will only ever have 0 or 1 items in it
一個簡單的解決方法是使用Paint Listener
,即使窗口隱藏在其他窗口後面,該工作仍然有效。 主要的缺點是當UI上的內容不可見時(例如當通過滾動可訪問TableItem時),那麼將不會工作。該解決方案適用於Win7和eclipse 3.7.2。
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
public class TableTest {
static int counter = 0;
public static void main(String[] args) {
final Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
shell.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
final Table table = new Table(shell, SWT.BORDER);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
table.setHeaderVisible(true);
table.setLinesVisible(true);
table.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
System.out.println(((Table)e.widget).getItemCount() > 0);
}
});
TableColumn column = new TableColumn(table, SWT.LEFT);
column.setWidth(180);
column.setText("Test Column");
Button button = new Button(shell, SWT.PUSH);
button.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
button.setText("Add item");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText("" + counter++);
if(counter > 10) {
table.clearAll();
counter = 0;
}
}
});
display.timerExec(1000, new Runnable() {
public void run() {
if(table.isDisposed()) return;
TableItem item = new TableItem(table, SWT.NONE);
item.setText("" + counter++);
if(counter > 10) {
table.clearAll();
counter = 0;
}
display.timerExec(1000, this);
}
});
shell.setSize(220, 300);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
注:的LVN_INSERTITEM沒有在SWT Table小部件的支持。檢查Table小部件中的windowProc
方法。
不錯!那就是訣竅。非常感謝你! – crhurley4 2013-04-25 15:25:31
@ crhurley4 - 不客氣。 – Favonius 2013-04-25 16:13:52