如何在SWT表中添加动态行?

时间:2016-01-14 08:20:36

标签: java swt

enter image description here

在上表中,如何通过点击ADD.. - 按钮添加动态行,选择行并点击DEL.. - 按钮

删除行

1 个答案:

答案 0 :(得分:0)

以下代码(改编自Snippet 101)符合您的要求:

final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());

final Table table = new Table(shell, SWT.BORDER | SWT.MULTI);

final Button addButton = new Button(shell, SWT.PUSH);
addButton.setText("Add item");
addButton.addListener(SWT.Selection, new Listener() {
  @Override
  public void handleEvent(Event event) {
    final TableItem item = new TableItem(table, SWT.NONE, 0);
    item.setText("*** New Item " + table.indexOf(item) + " ***");
  }
});

final Button deleteButton = new Button(shell, SWT.PUSH);
deleteButton.setText("Delete item");
deleteButton.addListener(SWT.Selection, new Listener() {
  @Override
  public void handleEvent(Event event) {
    final TableItem[] selectedItems = table.getSelection();
    for (final TableItem item : selectedItems) {
      item.dispose();
    }
  }
});

final Rectangle clientArea = shell.getClientArea();
table.setBounds(clientArea.x, clientArea.y, 200, 200);
for (int i = 0; i < 12; i++) {
  final TableItem item = new TableItem(table, SWT.NONE);
  item.setText("Item " + i);
}
shell.pack();
shell.open();
while (!shell.isDisposed()) {
  if (!display.readAndDispatch()) {
    display.sleep();
  }
}
display.dispose();

添加按钮在顶部添加新项目(索引0),删除按钮删除所有选定项目(如果有)。