swt table增加和删除行,第一列为ccombo控件,第二列为String,完整代码和注释
时间: 2023-07-15 17:13:52 浏览: 111
下面是 SWT Table 添加和删除行的示例代码,其中第一列使用了 CCombo 控件,第二列是一个字符串:
```java
import org.eclipse.swt.SWT;
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.CCombo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
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 TableExample {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("SWT Table Example");
shell.setLayout(new GridLayout(2, false));
// create a label for the combo box
Label label = new Label(shell, SWT.NONE);
label.setText("Select an option:");
// create a combo box with some options
CCombo combo = new CCombo(shell, SWT.READ_ONLY);
combo.setItems(new String[] { "Option 1", "Option 2", "Option 3" });
// create a button to add a new row to the table
Button addButton = new Button(shell, SWT.PUSH);
addButton.setText("Add Row");
// create a button to delete the selected row from the table
Button deleteButton = new Button(shell, SWT.PUSH);
deleteButton.setText("Delete Row");
// create a table with two columns
final Table table = new Table(shell, SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
table.setLinesVisible(true);
table.setHeaderVisible(true);
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
data.horizontalSpan = 2;
table.setLayoutData(data);
TableColumn column1 = new TableColumn(table, SWT.NONE);
column1.setText("Option");
column1.setWidth(100);
TableColumn column2 = new TableColumn(table, SWT.NONE);
column2.setText("Text");
column2.setWidth(100);
// add a new row to the table when the add button is clicked
addButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(0, combo.getText());
item.setText(1, "New Row");
}
});
// delete the selected row from the table when the delete button is clicked
deleteButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
int index = table.getSelectionIndex();
if (index != -1) {
table.remove(index);
}
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
```
在这个示例代码中,我们创建了一个包含两列的 SWT Table。第一列使用了 CCombo 控件,用户可以从预定义的选项中选择一个值。第二列是一个字符串,用户不需要输入。我们还添加了一个 "Add Row" 按钮,当用户单击它时,将添加一个新行到表中。我们还添加了一个 "Delete Row" 按钮,当用户单击它时,将删除选中的行。
阅读全文