addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
}
public void mouseDown(MouseEvent e) {
int row = (ey cy) / lineHeight; //計算選中的行
if (row >= ) {
oldRowSel = rowSel;
rowSel = row;
}
if (oldRowSel != rowSel) { // 重畫舊的和新的選擇項
((Canvas) egetSource())redraw(cx (ey / lineHeight)
* lineHeight maxX lineHeight false);
((Canvas) egetSource())redraw(cx (oldRowSel + cy
/ lineHeight)
* lineHeight maxX lineHeight false);
}
selectionChanged();
}
public void mouseUp(MouseEvent e) {
}
});
當我們的控件獲得焦點時選中的列表項需要有虛框表示控件得到焦點當獲得或失去焦點是我們這裡只需要簡單的通知選中的項重畫
addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
((Canvas) e
getSource())
redraw(cx
rowSel * lineHeight
maxX
lineHeight
true);
}
public void focusLost(FocusEvent e) {
((Canvas) e
getSource())
redraw(cx
rowSel * lineHeight
maxX
lineHeight
true);
}
});
我們在繪制每一個列表項時可以加入判斷當前控件是否得到焦點如果控件得到了焦點我們就在選中的項目上畫一個虛框下面是我們繪制一個列表項的代碼注意在代碼的最後繪制焦點的虛框
void onPaint(GC gc
int row
int beginx
int beginy
boolean isSelected) {
Color initColor = gc
getBackground();
Color initForeColor = gc
getForeground();
if (isSelected) {
gc
setBackground(Display
getCurrent()
getSystemColor(
SWT
COLOR_LIST_SELECTION));
gc
fillRectangle(beginx
beginy
maxX
lineHeight);
gc
setForeground(Display
getCurrent()
getSystemColor(
SWT
COLOR_LIST_SELECTION_TEXT));
} else {
gc
setBackground(initColor);
}
gc
drawString((String) colorNames
get(row)
beginx +
beginy);
Color color = Display
getCurrent()
getSystemColor(
((Integer) colors
get(row))
intValue());
gc
setBackground(color);
gc
fillRectangle(beginx +
beginy +
lineHeight
);
gc
setBackground(initColor);
gc
setForeground(initForeColor);
if (isFocusControl() && isSelected)
gc
drawFocus(cx
beginy
maxX
lineHeight);
}
[] [] [] [] [] []
From:http://tw.wingwit.com/Article/program/Java/ky/201311/28984.html