1

我有一个从父 shell 创建的自定义 swt shell。我需要设置外壳相对于其父复合材料的位置。但是,因为我在 shell 上调用 setLocation(x, y),所以 setLocation(x,y) 现在相对于 clientArea 起作用。有没有办法让 shell.setLocation(x,y) 相对于 PARENT 复合而不是 clientArea 工作?. 即,即使父复合材料在屏幕上调整大小/移动,自定义外壳也应始终保留在其父复合材料中。

示例代码片段:

 class CustOmShellTest {
    customShell = new Shell(parent.getShell(), SWT.TOOL | SWT.CLOSE);
        customShell.setLayout(new GridLayout());
        customShell.setBackgroundMode(SWT.INHERIT_FORCE);
        customShell.setSize(300, 400);
        customShell.setLocation(parent.getBounds().x, parent.getBounds().y );

}

new CustOmShellTest(parentOfThisInstanceComposite);

//这是相对于 disPlay 定位的实例。我希望它相对于//相对于 parentOfThisInstanceComposite 进行定位

任何帮助表示赞赏!谢谢。

4

2 回答 2

0

下面的代码让我得到了自定义 shell 的实际父级的相对位置。这需要通过 RESIZE 事件来完成,即

//parent.toDisplay(parent.getLocation().x , // parent.getLocation().y)

customShell.addListener(SWT.RESIZE, new Listener() {
            public void handleEvent(final Event event) {

customShell.setLocation(parent.toDisplay(parent.getLocation().x ,
                        parent.getLocation().y));                
        customShell.layout();
                parent.layout();
            }
        });

感谢您的输入

于 2013-11-06T02:24:54.730 回答
0

我创建了一个片段,您的自定义外壳被锚定到主外壳中的一个组件。我称该组件为“锚”。用您的控件替换它。

这里的神奇方法是Control.toDisplay(),要保持位置,您必须添加调整大小和移动侦听器。

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());

    final Label label = new Label(shell, SWT.NONE);
    label.setText("anchor");
    label.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));

    final Shell customShell = new Shell(shell, SWT.TOOL | SWT.CLOSE);
    customShell.setLayout(new GridLayout());
    customShell.setBackgroundMode(SWT.INHERIT_FORCE);
    customShell.setSize(300, 400);
    customShell.setVisible(true);

    final Listener listener = new Listener() {
        @Override
        public void handleEvent(Event event) {
            final Rectangle bounds = label.getBounds();
            final Point absoluteLocation = label.toDisplay(bounds.width, bounds.height);
            customShell.setLocation(absoluteLocation);
            if (shell.getMaximized()) {
                display.asyncExec(new Runnable() {
                    @Override
                    public void run() {
                        handleEvent(null);
                    }
                });
            }
        }
    };
    shell.addListener(SWT.Resize, listener);
    shell.addListener(SWT.Deiconify, listener);
    shell.addListener(SWT.Move, listener);
    customShell.addListener(SWT.Move, listener);

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

请注意,我还在自定义外壳上添加了侦听器,以确保它永远不会移动。当父 shell 移动时,自定义 shell 也会随之移动。

于 2013-11-05T20:31:50.357 回答