将 Jframe 对齐到不同的位置

aligning Jframe to different locations

我知道 java 在 JVM 上 运行 使其独立于平台。我最近在学习开发桌面应用程序,所以我的问题是:如何让我的应用程序屏幕恰好在顶部 right/left 或底部 right/left 或中心弹出?比如,对于右上角我们可以简单地使用:
frame.setLocation(0,0)
或者对于中心,我在这里找到的一种很好的、​​独立于平台的方式是:
frame.setLocationRelativeTo(null)

但是其他 3 个边缘呢?我看到了一些使用其他 classes(dimensions/point class)或包的大块代码,但它们要么太复杂,要么是一个特定的方向(就像我在这里看到的一个答案很容易让我的应用程序在底部弹出;但如果我的老师说他想在顶部看到应用程序弹出窗口,我必须重新编写我的整个解决方案)。我也尝试使用 getmaximumsize().height/width 但没有用。

我希望有人能帮我处理所有可能的边缘和中心位置的代码(即使它使用其他 classes/packages;只要它满足上述所有情况,欢迎您的回答) .和另一个小问题:在 java 中是否有任何变量 MAXWINDOW,例如,我的 window 屏幕是 15.6",下面的 0.5" 工具栏是我的 250*100 像素 jframe 的理想底部是 0,15.5" ,一个变量告诉那个特定的理想值?并根据我的工具栏的位置或具有 smaller/bigger 大小和工具栏位置的操作系统更改它的值??
之所以想到它,是因为感觉像这样的变量可能非常方便,并且增加了 java 的平台独立性。

编辑...
感谢@bjorn 和@madprogrammer 的回答太好了。考虑到平台独立子句,我从没想过 "getting taskbar-free window size for location" 问题需要这么大的代码。我觉得比约恩的回答目前让我完全满意。但是对于我引用的问题,mad 的回答更准确(或精确?呃我的英语)。

您可以通过以下代码获取屏幕尺寸:

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();

在您的框架中,您可以通过从屏幕宽度中减去 JFrame 的宽度来设置相应的位置。高度同上。

Toolkit.getDefaultToolkit().getScreenSize(); returns 默认屏幕的全屏尺寸,它不考虑其他屏幕元素,如停靠栏或任务栏,它们并不总是位于屏幕底部,也不总是相同大小

更好的解决方案可能是使用 Toolkit.getDefaultToolkit().getScreenInsetsGraphicsConfiguration

public static Rectangle getScreenViewableBounds(Window window) {
    return getScreenViewableBounds((Component) window);
}

public static Rectangle getScreenViewableBounds(Component comp) {
    return getScreenViewableBounds(getGraphicsDevice(comp));
}

public static Rectangle getScreenViewableBounds(GraphicsDevice gd) {
    Rectangle bounds = new Rectangle(0, 0, 0, 0);
    if (gd == null) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        gd = ge.getDefaultScreenDevice();
    }

    if (gd != null) {
        GraphicsConfiguration gc = gd.getDefaultConfiguration();
        bounds = gc.getBounds();

        Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
        bounds.x += insets.left;
        bounds.y += insets.top;
        bounds.width -= (insets.left + insets.right);
        bounds.height -= (insets.top + insets.bottom);
    }

    return bounds;
}

这将 return 特定屏幕的 "safe viewable" 范围。如果你传递它null,它将使用"default"屏幕

// Safe viewable area for default screen
Rectangle bounds = getScreenViewableBounds(null);
int x = bounds.x + ((bounds.width - getWidth());
int y = bounds.y + ((bounds.width - getHeight());

setLocation(x, y);

这会将 window 放在 window 的 bottom/right 手部位置,但是,将其与任务栏对齐(因为大多数人都将其与底部对齐)

对于像我这样把任务栏放在屏幕顶部的怪人来说

// Safe viewable area for default screen
Rectangle bounds = getScreenViewableBounds(null);
int x = bounds.x;
int y = bounds.y;

setLocation(x, y);

将 window 放置在可视项的 top/left 角,与任务栏下方对齐

是的,我见过太多开发人员使用 setLocation(0, 0) 并将 window 放在 taskbar/menu 栏下,他们的名字变成了 "mud"