Toolkit.getDefaultToolkit().getScreenSize();
返回默认屏幕的全屏幕尺寸,但它没有考虑到其他屏幕元素,如底座或任务栏,它并不总是在屏幕的底部,并非总是同样大小
一个更好的解决方案可能是使Toolkit.getDefaultToolkit().getScreenInsets
和GraphicsConfiguration
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;
}
这种使用会返回一个特定画面的“安全可视”的范围。如果你通过它null
,它将使用“默认”屏幕
// 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);
这将放置在窗口的底部/右边位置的窗口,但是,把它对准到任务栏(因为大多数人都有它沿底部)
对于怪异的人,像我一样,谁把任务栏在屏幕
// Safe viewable area for default screen
Rectangle bounds = getScreenViewableBounds(null);
int x = bounds.x;
int y = bounds.y;
setLocation(x, y);
的顶部将放置在可视的顶部/左上角的窗口,下面排列对齐任务栏
是的,我见过太多的开发人员使用setLocation(0, 0)
并把窗口任务栏/菜单栏下,他们的名字变成了“泥”
*“我甚至可以使用此代码段用于获取一个最大大小的窗口” * - 我会查看'JFrame#setExtendedState',并以独立于平台的方式最大化窗口,这将不会将窗口的任何部分放置在任务栏/ dock的底部 – MadProgrammer