ITeye博客

SWT对话框系列:让对话框支撑方向键选择

vwpolo · 2009-12-09 08:33 · SWT/JFace · 企业架构 · Markdown

在SWT 3.3中弹出的对话框比如确认对话框,可以通过Tab键在对话框按钮之间来回选择,但是无法通过键盘方向键来选择,这就让Windows的爱好者很不习惯,其实我自己使用起来也不习惯。 <!--endfragment-->  其实让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;
  }

<!--endfragment-->

上面方法的defaultTrue是指焦点是否默认在"确认"按钮上面。
<!--endfragment--><!--endfragment--><!--endfragment--><!--endfragment-->

使用方法:

<!--endfragment-->

MessageDialog2.openQuestion(getShell(),”确认操作”,”是否要执行XX操作?”,false);

<!--endfragment-->

 
  默认焦点为”否”按钮上,当然,你也可以使用键盘方向键选择"是"按钮

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。