严格基于此,“表中只会有 0 或 1 个项目”,一个简单的解决方法是使用 a PaintListener
,即使窗口隐藏在其他窗口后面也可以。主要缺点是当内容在 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();
}
}
注意: SWT小部件不支持LVN_INSERTITEMTable
。检查小部件windowProc
中的方法Table
。