指定JFace.Dialog初始化的位置

来源:互联网 发布:我的世界苹果版枪械js 编辑:程序博客网 时间:2024/06/05 10:38
作者:dearwolf 发表于:javaeye 原文链接:http://www.javaeye.com/topic/40872
目的1:打开一个新的对话框时,如何设定它和父对话框的相对位置?比如在登录对话框有一个“创建新帐号”的按钮,用户点击以后,就出现新的对话框用于注册,请问如何能让新的对话框和旧对话框排列的整齐一些?应该是能设定二者的相对位置吧?

最开始,以为要用Shell.setLocation来设置,但是对于一个Dialog而言,它的Shell在什么时候才能初始化呢?

我在构造函数里面,configureShell(Shell newShell)方法里面,Control createDialogArea(Composite parent)方法里面都调用过了this.getShell方法想得到当前的Shell,结果都抛出空指针异常....

后来看书发现,应该重写protected Point getInitialLocation(Point initialSize)方法

比如,在最开始的例子中,在第二个对话框中我重写了该方法,代码如下:
  1. protected Point getInitialLocation(Point initialSize) {  
  2.         Point location = new Point(this.getParentShell().getLocation().x  
  3.                 + this.getParentShell().getBounds().width, this  
  4.                 .getParentShell().getLocation().y  
  5.                 + this.getParentShell().getBounds().height  
  6.                 - this.getInitialSize().y);  
  7.         return location;  
  8.     } 
其结果就是两个对话框底部对齐的平行排列:)

目的2: 登陆对话框要记住上次的位置。

想了半天,好像只能用IPreferenceStore来做了,在继承了AbstractUIPlugin的类中放入两个常量: 
  1. public static final String LOGINDIALOG_POSITION_X = "LOGINDIALOG_POSITION_X";  
  2.   
  3. public static final String LOGINDIALOG_POSITION_Y = "LOGINDIALOG_POSITION_Y"
然后重写两个方法: 
  1. @Override  
  2.     protected Point getInitialLocation(Point initialSize) {  
  3.   
  4.         String xposition = preferenceStore  
  5.                 .getString(Peer68TPlugin.LOGINDIALOG_POSITION_X);  
  6.         String yposition = preferenceStore  
  7.                 .getString(Peer68TPlugin.LOGINDIALOG_POSITION_Y);  
  8.         if (xposition == null || yposition == null || xposition == ""  
  9.                 || yposition == "") {  
  10.             return super.getInitialLocation(initialSize);  
  11.         } else {  
  12.             return new Point(Integer.parseInt(xposition), Integer  
  13.                     .parseInt(yposition));  
  14.         }  
  15.     }  
  16.   
  17.     @Override  
  18.     public boolean close() {  
  19.         preferenceStore.setValue(Peer68TPlugin.LOGINDIALOG_POSITION_X, this  
  20.                 .getShell().getLocation().x);  
  21.         preferenceStore.setValue(Peer68TPlugin.LOGINDIALOG_POSITION_Y, this  
  22.                 .getShell().getLocation().y);  
  23.         return super.close();  
  24.     } 
大功告成!