1

我在代码上添加了列:

String[] titles = {"Nazwa", "Uzytkownik", "Haslo"};

for(int i=0; i<titles.length; i++){
    TableColumn column = new TableColumn(table, SWT.NULL);
    column.setText(titles[i]);
}

接下来,我在所述列中添加了项目:

String[][] a = new String[passwords.length][3];
for(int i=0; i<passwords.length; i++){
    a[i] = passwords[i].split(":");
}
for(int i=0; i<passwords.length; i++){
    TableItem item = new TableItem(table, SWT.NULL);
    //item.setText(Integer.toString(i));            
    for(int j=0; j<a[i].length; j++){
        item.setText(j, a[i][j]);
    }
}

现在,我想从第二列中获取选定的项目。我添加了 TableCursor 和 KeyListener:

tableCursor.addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
        if(e.character == 'c') {
            Point p = tableCursor.getLocation();
            //for(int i=0; i<selection.length; i++){
                TableItem item = table.getItem(p);
                if(item != null){
                MessageBox message = new MessageBox(shell, SWT.ICON_ERROR);
                message.setMessage(item.toString());
                message.open();
            }

        }
    }
});

现在,例如,当我从第二列中选择项目时,它看不到第二列中的任何内容,只看到第一列中的项目。有什么问题?

4

1 回答 1

1

问题是您尝试在表中查找所选项目/列的方式。

这是一个完全符合您要求的示例:

public static void main(String[] args)
{
    Display display = Display.getDefault();
    final Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());

    final Table table = new Table(shell, SWT.NONE);
    table.setHeaderVisible(true);

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

    /* Create items */
    for (int i = 0; i < 10; i++)
    {
        TableItem item = new TableItem(table, SWT.NONE);
        item.setText(new String[] { "Row" + i + "Col1", "Row" + i + "Col2", "Row" + i + "Col3" });
    }

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

    table.addListener(SWT.MouseUp, new Listener()
    {
        @Override
        public void handleEvent(Event event)
        {
            Point pt = new Point(event.x, event.y);
            TableItem item = table.getItem(pt);
            if (item != null)
            {
                /* Iterate over all columns and check if event is contained */
                for (int col = 0; col < table.getColumnCount(); col++)
                {
                    Rectangle rect = item.getBounds(col);
                    if (rect.contains(pt))
                    {
                        System.out.println(item.getText(col));
                    }
                }
            }
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}
于 2013-02-13T17:23:32.327 回答