我将SWT向导页面作为父外壳程序,用于在单击按钮时创建另一个外壳程序,我正在编写以下代码
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);
但是由于子外壳意味着此外壳未放置在作为父外壳的SWT向导的中心,为什么?
Rectangle screenSize = display.getPrimaryMonitor().getBounds();
shell.setLocation((screenSize.width - shell.getBounds().width) / 2, (screenSize.height - shell.getBounds().height) / 2);
如果您正在编写对话框或子组件,则可能要使用getParent而不是询问显示器作为主监视器,以便该窗口位于多个监视器设置的当前屏幕中央。
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));
我认为最好的方法是将样式SWT.SHEET用于此类对话框。
我只是遇到了同样的问题。我得到的解决方案有些不同。这可能会帮助其他人解决相同的问题。上下文是一个外壳(hoverShell),它在父(外壳)上悬停了几秒钟,显示一条消息。
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,那是我所相信的。可能取决于是否计算了窗口的顶部边框。