任意设置colorDialog的初始显示位置

本文提供一种思路,用于设置ColorDialog的弹出时的显示位置。先看一下ColorDialog这个类的构造。

public ColorDialog(Shell parent)
    {
        this(parent, 32768);
    }
    public ColorDialog(Shell parent, int style)
    {
        super(parent, style);
        checkSubclass();
    }

32768 在org.eclipse.swt中对应的值是 public static final int PRIMARY_MODAL = 32768;意思就是模式化显示窗体。

ColorDialog默认以parent的x,y为显示位置。但是如果是包含多个viewer的复杂窗体,而我们又想让ColorDialog在鼠标点击某个按键时在按键附近显示,这时问题就来啦。由于不论窗口有多少个,shell都是一个。所以,如论你从哪里获得shell,用于构造ColorDialog后, ColorDialog都只出现在屏幕的左上角。

整个ColorDialog中也就6个方法。根本不知道怎么设置ColorDialog的初始化位置。

后来研究了一下eclipse的颜色选择器,受到了点启发,如下图。


首选项作为一个dialog,当你点击红框中的颜色按钮时,弹出“颜色”选择器colordialog。而colordialog的默认显示位置是dialog的左上角。
于是我就想了个歪点子,我不能控制colordialog的显示位置,但是我可以任意控制dialog的弹出位置,于是自己做一个dialog,在他的createContents()方法中声明并打开colordialog,然后马上设置dialog的setVisible(false);让它消失,然后在colordialog返回rgb结果后销毁掉这个窗口,结果效果非常不错。

下面是代码片段,首先是dialog类中的代码:

/**
  * Open the dialog
  * @return the result
  */
public Object open() {
  createContents();
  shell.open();
  shell.layout();
  /*
  * 此处删除了while循环。
  */
  shell.dispose();
  return result;//返回colordialog选择的结果 }
/**
  * Create contents of the dialog
  */
protected void createContents() {
  shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
  shell.setSize(232, 275);//这里随便设置了无所谓
  shell.setVisible(false);//设置让它消失
  setScreenPoint(shell);/*设置窗口居中显示,你想让colordialog在哪里显示,直接设置shell.setLocation就可以了*/
  ColorDialog c = new ColorDialog(shell);    
  result = c.open();  
  //
}

/**
  * 设置窗口屏幕居中
  * @param shell
  */
protected void setScreenPoint(Shell shell)
{
  int width = shell.getMonitor().getClientArea().width;
  int height = shell.getMonitor().getClientArea().height;
  int x = shell.getSize().x;
  int y = shell.getSize().y;
  if(x > width)
  {
  shell.getSize().x = width;
  }
  if(y > height)
  {
  shell.getSize().y = height;
  }
  shell.setLocation((width - x) / 2, (height - y) / 2);  
}

效果图如下,点击红色方框内的文字 弹出颜色选择框,位置就在文字附近。
选择一种颜色后,对应的绿色文字会变成你选择的颜色。我选择了蓝色,原来的绿字变成了蓝色。


当然对于高手来讲,解决问题的方法有很多种,你大可以去重写colordialog,甚至display,
而小弟此法纯属歪门邪道,不过好处是省心,简单,而且,不走寻常路,也是程序人生中的一种乐趣。

posted @ 2012-05-12 11:38  辣椒粉  阅读(1580)  评论(0编辑  收藏  举报