JAVA.SWT/JFace: SWT高级控件之表格(五)

2014-11-24 02:33:33 · 作者: · 浏览: 9
eCursor(table, SWT.NONE);
//创建可编辑的控件
final ControlEditor editor = new ControlEditor(cursor);
editor.grabHorizontal = true;
editor.grabVertical = true;
//为TableCursor对象注册事件
cursor.addSelectionListener( new SelectionAdapter() {
//但移动光标,在单元格上单击回车所触发的事件
public void widgetDefaultSelected(SelectionEvent e) {
//创建一个文本框控件
final Text text = new Text(cursor, SWT.NONE);
//获得当前光标所在的行TableItem对象
TableItem row = cursor.getRow();
//获得当前光标所在的列数
int column = cursor.getColumn();
//当前光标所在单元格的值赋给文本框
text.setText(row.getText(column));
//为文本框注册键盘事件
text.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
//此时在文本框上单击回车后,这是表格中的数据为修改后文本框中的数据
//然后释放文本框资源
if (e.character == SWT.CR) {
TableItem row = cursor.getRow();
int column = cursor.getColumn();
row.setText(column, text.getText());
text.dispose();
}
//如果在文本框中单击了ESC键,则并不对表格中的数据进行修改
if (e.character == SWT.ESC) {
text.dispose();
}
}
});
//注册焦点事件
text.addFocusListener(new FocusAdapter() {
//当该文本框失去焦点时,释放文本框资源
public void focusLost(FocusEvent e) {
text.dispose();
}
});
//将该文本框绑定到可编辑的控件上
editor.setEditor(text);
//设置文本框的焦点
text.setFocus();
}
//移动光标到一个单元格上所触发的事件
public void widgetSelected(SelectionEvent e) {
table.setSelection(new TableItem[] { cursor.getRow()});
}
});
cursor.addMouseListener(new MouseListener() {

@Override
public void mouseDoubleClick(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mouseDown(MouseEvent e) {
if (e.button==3) { // 右键按下,显示右键菜单
menu.setVisible(true);
}
}

@Override
public void mouseUp(MouseEvent e) {
// TODO Auto-generated method stub

}

});
// ******************************************************/
//重新布局表格
for (int i=0; i table.getColumn (i).pack ();
}
// /****************************************************
//为单元格注册选中事件
table.addSelectionListener( new SelectionAdapter(){
public void widgetSelected(SelectionEvent e) {
//获得所有的行数
int total = table.getItemCount();
//循环所有行
for ( int i=0;i TableItem item = table.getItem(i);
//如果该行为选中状态,改变背景色和前景色,否则颜色设置
if (table.isSelected( i )){
item.setBackground( sShell.getDisplay().getSystemColor( SWT.COLOR_RED));
item.setForeground( sShell.getDisplay().getSystemColor( SWT.COLOR_WHITE));
}else {
item.setBackground( null );
item.setForeground( null );
}
}
}

});
// ******************************************************/
}

public static void main(String[] args) {
//调用主窗口
Display di