我在代码上添加了专栏:
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();
}
}
}
});
现在,例如,当我从第二列中选择 item 时,它从第二列中看不到任何内容,只有第一列中的 item 。有什么问题?
答案 0 :(得分: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();
}