在SWT 3.3中彈出的對話框比如確認對話框,可以通過Tab鍵在對話框按鈕之間來回選擇,但是無法通過鍵盤方向鍵來選擇,這就讓Windows的愛好者很不習慣,其實我自己使用起來也不習慣。
其實讓SWT的對話框支持方向鍵選擇有好幾種方案
A方案:將平臺遷移到Eclipse 3.4+,這個方法在SWT 3.4+中解決了
B方案:可以自己實現這個功能!
我們可以繼承 org.eclipse.jface.dialogs.MessageDialog 這個類,比如就叫MessageDialog2,然后重寫父類中的 createButtonsForButtonBar(Composite parent) 方法,比如可以參考我的實現方法:
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
int columns = ((GridLayout) parent.getLayout()).numColumns;
if(columns < 2)
return;
for (int i = 0; i < columns; i++) {
Button button = getButton(i);
int index = (i + 1 < columns ? i + 1 : i-1);
final Button otherButton = getButton(index);
button.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.ARROW_RIGHT || e.keyCode == SWT.ARROW_LEFT) {
otherButton.setFocus();
}
}
});
}
}
然后在MessageDialog2方法重寫 openQuestion(Shell parent, String title, String message) 方法,
參考實現:
public static boolean openQuestion(Shell parent, String title, String message, boolean defaultTrue) {
MessageDialog2 dialog = new MessageDialog2(UIUtil.getActiveShell(), title, null, message, QUESTION, new String[] {
IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, defaultTrue ? 0 : 1);
return dialog.open() == 0;
}
上面方法的defaultTrue是指焦點是否默認在"確認"按鈕上面。
使用方法:
MessageDialog2.openQuestion(getShell(),”確認操作”,”是否要執行XX操作?”,false);
默認焦點為”否”按鈕上,當然,你也可以使用鍵盤方向鍵選擇"是"按鈕