且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用swt向表中添加一行

更新时间:2023-12-06 17:19:16

以下是一个简单的工作示例,说明如何在按下按钮时向表格添加项目:

Here's a simple working example of how to add items to a table when a button is pressed:

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    RowLayout layout = new RowLayout(SWT.VERTICAL);
    layout.fill = true;
    shell.setLayout(layout);
    shell.setSize(200, 200);
    final Table table = new Table(shell, SWT.BORDER | SWT.MULTI);
    final Text text = new Text(shell, SWT.SINGLE | SWT.BORDER);
    text.setText("blahblah text");
    Button button = new Button(shell, SWT.PUSH);
    button.setText("Push me");

    // this is the code you want
    button.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            TableItem item = new TableItem(table, SWT.NONE);
            item.setText(text.getText());
        }
    });

    for (int i = 0; i < 5; i++) {
        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();
}

如果必须使用 TableViewer 系统来添加项目,则需要修改作为输入传递给查看器的任何对象.如果您使用 IStructuredContentProvider 作为查看器的内容提供程序,getElements 方法将返回一个数组,该数组将继续成为您的表的行.要在输入更改后更新它,只需调用 viewer.refresh()

If you must use the TableViewer system to add items, you need to modify whatever Object is passed into the viewer as its input. If you use an IStructuredContentProvider as your viewer's content provider, the getElements method returns an array that goes on to become your table's rows. To update it after a change to the input, just call viewer.refresh()