Java 在其父外壳的中心生成swt外壳

Java 在其父外壳的中心生成swt外壳,java,swt,Java,Swt,我将SWT向导页面作为我的父shell,用于在单击按钮时创建另一个shell,我正在编写以下代码 Shell permissionSetShell = new Shell(Display.getCurrent().getActiveShell(), SWT.CENTER|SWT.DIALOG_TRIM|SWT.APPLICATION_MODAL); permissionSetShell.setText(PropertyClass.getPropertyLabel(QTLConstants.PER

我将SWT向导页面作为我的父shell,用于在单击按钮时创建另一个shell,我正在编写以下代码

Shell permissionSetShell = new Shell(Display.getCurrent().getActiveShell(), SWT.CENTER|SWT.DIALOG_TRIM|SWT.APPLICATION_MODAL);
permissionSetShell.setText(PropertyClass.getPropertyLabel(QTLConstants.PERMISSION_SET_COLUMN_LABEL));

// Add shell to the center of parent wizard
permissionSetShell.setLayout(componentsRenderer.createGridLayout(1, false, 0, 5, 0, 0));    
Monitor primary = Display.getCurrent().getPrimaryMonitor ();
Rectangle bounds = primary.getBounds ();
Rectangle rect = Display.getCurrent().getActiveShell().getBounds ();
int x = bounds.x + (bounds.width - rect.width) / 2;
int y = bounds.y + (bounds.height - rect.height)/2;              
permissionSetShell.setLocation (x, y);

但由于子shell意味着此shell不位于SWT向导的中心,这就是父shell为什么?

如果您正在编写对话框或子组件,您可能希望使用getParent,而不是请求主监视器的显示,以便多个监视器设置的窗口位于当前屏幕的中心

Rectangle screenSize = display.getPrimaryMonitor().getBounds();
shell.setLocation((screenSize.width - shell.getBounds().width) / 2, (screenSize.height - shell.getBounds().height) / 2);
Rectangle parentSize = getParent().getBounds();
Rectangle shellSize = shell.getBounds();
int locationX = (parentSize.width - shellSize.width)/2+parentSize.x;
int locationY = (parentSize.height - shellSize.height)/2+parentSize.y;
shell.setLocation(new Point(locationX, locationY));

我认为最好是在这样的对话框中使用style SWT.SHEET。

我刚刚遇到了同样的问题。我得到的解决方案有点不同。这可能会帮助其他人解决同样的问题。上下文是一个shell(hoverShell),它在父级(shell)上悬停几秒钟,显示一条消息

    private void displayMessage(Shell shell, String message) {
      Shell hoverShell = new Shell(shell, SWT.ON_TOP);
      hoverShell.setLayout(new FillLayout());
      Label messageLabel = new Label(hoverShell, SWT.NONE);
      messageLabel.setText(message);
      Point shellLocation = shell.getLocation();
      hoverShell.pack();
      hoverShell.setLocation(shellLocation.x + (shell.getSize().x / 2) - (hoverShell.getSize().x / 2), shellLocation.y + 40);
      hoverShell.open();
      Display.getDefault().timerExec(2000, new Runnable() {

        @Override
        public void run() {
            hoverShell.dispose();
        }
    });
}
简言之,这是以下公式:

child_location.x=parent_location.x+.5*(parent_width.x)-.5*(child_width.x)


如果你想要y,那么我相信是完全一样的。可能取决于是否计算了窗口的上边框。

您是否检查了
bounds
rect
是否确实包含正确的信息?Baz,是的,它包含信息,但信息正确吗?我的问题是,这应该是公认的答案,因为现在多个监视器设置并不罕见,而且“+parentSize.x;“是至关重要的,另一个答案中没有。这将显示以屏幕为中心的对话框,而不是问题中要求的家长上方的对话框。