簡體   English   中英

在其父 shell 的中心生成 swt shell

[英]generating swt shell at the center of its parent shell

我有 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 沒有放置在父 shell 的 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。

我剛剛遇到了同樣的問題。 我得到的解決方案有點不同。 這可能會幫助其他有同樣問題的人。 上下文是一個 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 那么它和我相信的完全一樣。 可能取決於是否計算了窗口的頂部邊框。

嘗試、測試和工作的代碼:

int 寬度 = display.getClientArea().width; int height = display.getClientArea().height; shell.setLocation(((width - shell.getSize().x) / 2) + display.getClientArea().x, ((height - shell.getSize().y) / 2) + display.getClientArea(). y);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM