如何弄清楚JDialog显示在哪个屏幕上

gil*_*ras 7 java swing multiple-monitors center jdialog

我有一个非常大的应用程序,它有多个对话框.我的任务是确保一个不完全可见的对话框(因为用户将其从可见屏幕区域拉出)被移回屏幕中心.

当我只处理一个屏幕时,这没问题.它工作得很好......但是,这个应用程序的大多数用户在他们的桌面上有两个屏幕...

当我试图弄清楚对话框显示在哪个屏幕上并将其置于该特定屏幕上时,......好吧,它实际上是中心,但是在主屏幕上(可能不是屏幕上显示对话框).

为了向您展示我到目前为止的想法,这里的代码是......

 /**
 * Get the number of the screen the dialog is shown on ...
 */
private static int getActiveScreen(JDialog jd) {
    int screenId = 1;
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] gd = ge.getScreenDevices();
    for (int i = 0; i < gd.length; i++) {
        GraphicsConfiguration gc = gd[i].getDefaultConfiguration();
        Rectangle r = gc.getBounds();
        if (r.contains(jd.getLocation())) {
            screenId = i + 1;
        }
    }
    return screenId;
}

/**
* Get the Dimension of the screen with the given id ...
*/
private static Dimension getScreenDimension(int screenId) {
    Dimension d = new Dimension(0, 0);
    if (screenId > 0) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        DisplayMode mode = ge.getScreenDevices()[screenId - 1].getDisplayMode();
        d.setSize(mode.getWidth(), mode.getHeight());
    }
    return d;
}

/**
 * Check, if Dialog can be displayed completely ...
 * @return true, if dialog can be displayed completely
 */
private boolean pruefeDialogImSichtbarenBereich() {
    int screenId = getActiveScreen(this);
    Dimension dimOfScreen = getScreenDimension(screenId);
    int xPos = this.getX();
    int yPos = this.getY();
    Dimension dimOfDialog = this.getSize();
    if (xPos + dimOfDialog.getWidth() > dimOfScreen.getWidth() || yPos + dimOfDialog.getHeight() > dimOfScreen.getHeight()) {
        return false;
    }
    return true;
}

/**
 * Center Dialog...
 */
private void zentriereDialogAufMonitor() {
    this.setLocationRelativeTo(null);
}
Run Code Online (Sandbox Code Playgroud)

虽然调试我遇到的事实getActiveScreen()似乎并不像我那样工作; 它似乎总是返回2(这是一种废话,因为它意味着对话框总是显示在第二个监视器中......这当然不是事实).

任何人都知道如何将对话框放在实际显示的屏幕上?

Boa*_*ann 1

您的getActiveScreen方法有效,只是它使用包含窗口左上角的屏幕。如果您改用 Component.getGraphicsConfiguration(),它会告诉您哪个屏幕拥有最多窗口像素。setLocationRelativeTo(null)在这里没有帮助,因为它总是使用主屏幕。解决方法如下:

static boolean windowFitsOnScreen(Window w) {
    return w.getGraphicsConfiguration().getBounds().contains(w.getBounds());
}

static void centerWindowToScreen(Window w) {
    Rectangle screen = w.getGraphicsConfiguration().getBounds();
    w.setLocation(
        screen.x + (screen.width - w.getWidth()) / 2,
        screen.y + (screen.height - w.getHeight()) / 2
    );
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

JDialog jd;
...
if (!windowFitsOnScreen(jd)) centerWindowToScreen(jd);
Run Code Online (Sandbox Code Playgroud)

这将使对话框居中到最近的屏幕(监视器)。您可能需要确保首先首先显示/定位对话框。