SWT的Table不够强大,而且似乎有严重的性能问题。(貌似是调用OS的实现,但是在win7上面跑却非常慢,奇特!本地的性能不如虚拟机上跑的Swing)
好在SWT中可以嵌入AWT。
反正本人以前没有过多Swing的经验,但是在试玩了JTable之后发现确实很强大。
对于有兴趣的读者可以试一下,本文将分享如何使得JTable与JFace Data Binding Framework(下文中简称JDBF)一起协同工作。
通常像Table和List这种UI组件,展现的都是一个对象集合。JDBF 则为我们处理对象集合和UI界面的同步的问题。以List为例子,在Java中有java.util.List,而JFDB则提供了相应的
ObservableList类,这个类Wrap一个java.util.List,当你对其进行增删改时,与其绑定的UI组件会自动得到同步。但是ObservableList 的实现有个很大的问题就是对其的访问只限于其所属的Realm,这个Realm说白了就是SWT的UI线程,而当我们在SWT中嵌入AWT时,其中的AWT界面是跑在其自身的线程里面的。所以想要让JTable与JFace Data Binding Framework(下文中简称JDBF)一起协同工作还要解决多线程的问题。废话不多说了,直接上菜:
public class DOTableModel extends AbstractTableModel { /**
* the ObservableList instance to be shared with
*/
private ObservableList list;
private volatile Integer rowCount = null;
private volatile DOModel object;;
private final Object lock = new Object();
private static final long serialVersionUID = -8377145381412656796L;
public DOTableModel(ObservableList list){
this.list = list;
this.list.addListChangeListener(new IListChangeListener(){
@Override
public void handleListChange(ListChangeEvent event) {
for(ListDiffEntry de : event.diff.getDifferences()){
if(de.isAddition()){
DOTableModel.this.fireTableRowsInserted(de.getPosition(), de.getPosition());
}else{
DOTableModel.this.fireTableRowsDeleted(de.getPosition(), de.getPosition());
}
}
}
});
}
@Override
public int getRowCount() {
list.getRealm().exec(new Runnable(){
@Override
public void run() {
rowCount = list.size();
synchronized (lock) {
lock.notify();
}
}
});
synchronized (lock) {
while(rowCount == null){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return rowCount;
}
@Override
public int getColumnCount() {
return 11;
}
private void getObjectFromSWTRealm(final int rowIndex){
object = null;
list.getRealm().exec(new Runnable(){
@Override
public synchronized void run() {
object = (DOModel) list.get(rowIndex);
synchronized (lock) {
lock.notify();
}
}
});
synchronized (lock) {
while(object == null){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public Object getValueAt(final int rowIndex, int columnIndex) {
getObjectFromSWTRealm(rowIndex);
...
}
@Override
public void setValueAt(Object oValue, final int rowIndex, int columnIndex) {
getObjectFromSWTRealm(rowIndex);
...
}
@Override
public String getColumnName(int column) {
...
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
}
posted on 2012-04-05 23:46
West Farmer 阅读(694)
评论(2) 编辑 收藏