让Table显示信息用到的是TableItem
类。创建一个TableItem类对象,通过调用该对象的setText( new String[ ] )
方法可以显示一行数据,循环调用则可以显示多条不同的数据。
一、步骤:
1. 创建Table类 。最好将Table类设置为全局变量。并且设置该表格有多少列。在Table对象的基础上创建一列的类为TableColumn。可以创建多列。
Table table = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION); //创建一个表格
TableColumn tblclmnNewColumn = new TableColumn(table, SWT.NONE); //创建一个列
TableColumn tblclmnNewColumn_1 = new TableColumn(table, SWT.NONE); //创建的第二个列
2.创建TableItem类。记住,TableItem类就是这个表格的一行,并且new的时候需要传入这一行是属于哪一个Table对象,所以要传入上述的table。
TablItem item = new TableItem(table,SWT.NONE);
3.通过TableItem类显示信息。使用到的是TableItem类中的setText( new String[] )方法。传入的参数是一个String数组,按照顺序每一个String分别是当前行的第一列,第二列…。
也可以将第2,3步封装成一个方法来调用。
item.setText(new String[] {
"第一行数据",
"第二行数据"
});
二、代码示例:
前置:
import java.util.ArrayList;
import java.util.List;
public class Person {
String id ;
String name ;
Person(){
}
Person(String id , String name){
this.id = id;
this.name = name;
}
String getName() {
return this.name;
}
String getId() {
return this.id;
}
static List<Person> getData(){
List<Person> list = new ArrayList<Person>();
list.add( new Person("1001","zhangsan") );
list.add( new Person("1002","lisi") );
return list;
}
}
首先通过可视化工具创建一个Table,和表格的列。
然后在创建Table对象下方加上如下代码:
TableItem item = null;
List<Person> list = Person.getData(); //用于测试的
for(Person p: list) {
item = new TableItem(table,SWT.NONE);
item.setText(new String[] {
p.getId(),
p.getName()
});
}
则可以显示提供的list对象的数据了。
三、完整代码:
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
public class Test {
protected Shell shell;
private Table table;
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
try {
Test window = new Test();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(730, 630);
shell.setText("SWT Application");
table = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
table.setBounds(195, 127, 206, 250);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn tblclmnNewColumn = new TableColumn(table, SWT.NONE);
tblclmnNewColumn.setWidth(100);
tblclmnNewColumn.setText("ID");
TableColumn tblclmnNewColumn_1 = new TableColumn(table, SWT.NONE);
tblclmnNewColumn_1.setWidth(100);
tblclmnNewColumn_1.setText("Name");
TableItem item = null;
List<Person> list = Person.getData(); //用于测试的
for(Person p: list) {
item = new TableItem(table,SWT.NONE);
item.setText(new String[] {
p.getId(),
p.getName()
});
}
}
}