如何将选定行的值从tableviewer传递到SWT中的文本框

时间:2014-03-10 10:31:11

标签: java swt

我有一个有10行的表,我想要做的是:当我点击“修改”按钮时,我想将选定的表行值传递给相应的文本框。

我尝试了一些代码,这些代码并不能满足我的需求,

MainTable.addListener(SWT.Selection, new Listener() {
    public void handleEvent(Event e) {
        String string = "";
        TableItem[] selection = MainTable.getSelection();
        for (int i = 0; i < selection.length; i++)
            string += selection[i] + " ";
        final String Appname=string.substring(11, string.length()-2);
        System.out.println(Appname);
    }
});

上面的代码在Console中打印Selected行值,我想将这些值设置为Textboxes。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

以下是一些示例代码:

private static int        columns = 3;
private static List<Text> texts   = new ArrayList<>();

public static void main(String[] args)
{
    Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("StackOverflow");
    shell.setLayout(new GridLayout(columns, false));

    Table table = new Table(shell, SWT.FULL_SELECTION);
    table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, columns, 1));
    table.setHeaderVisible(true);

    /* Create columns */
    for (int col = 0; col < columns; col++)
    {
        new TableColumn(table, SWT.NONE).setText("Col " + col);
    }

    /* Create cells */
    for (int row = 0; row < 10; row++)
    {
        TableItem item = new TableItem(table, SWT.NONE);

        for (int col = 0; col < table.getColumnCount(); col++)
        {
            item.setText(col, "Cell " + row + " " + col);
        }
    }

    /* Pack columns */
    for (int col = 0; col < table.getColumnCount(); col++)
    {
        table.getColumn(col).pack();
    }

    /* Create the Text fields */
    for (int col = 0; col < columns; col++)
    {
        Text text = new Text(shell, SWT.BORDER);
        texts.add(text);
    }

    /* Listen for selection */
    table.addListener(SWT.Selection, new Listener()
    {
        @Override
        public void handleEvent(Event e)
        {
            Table table = (Table) e.widget;
            TableItem item = table.getItem(table.getSelectionIndex());

            /* Fill the texts */
            for (int col = 0; col < table.getColumnCount(); col++)
            {
                texts.get(col).setText(item.getText(col));
            }
        }
    });

    shell.pack();
    shell.open();

    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

看起来像这样:

enter image description here