Determine height of screen in Java

2019-08-29 11:14发布

问题:

I have my JFrame in full screen mode using the following:

setExtendedState(JFrame.MAXIMIZED_BOTH);
setUndecorated(true);

And I want to know the height. Note that Toolkit.getDefaultToolkit().getScreenSize() does not work because I'm on a Mac and the real height should exclude the height of the Mac bar thing at the top of the screen.

And in the case of Windows, for example, the height should exclude the start bar. Hence, I want to know the true height of the window space I have.

回答1:

I use this

public static Rectangle getScreenViewableBounds() {

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();

    Rectangle bounds = new Rectangle(0, 0, 0, 0);

    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;

}

To determine the "safe" screen bounds. This takes into consideration the screen insets and produces a rectangle of a "safe" viewable area...

Updated

After a little testing, I'm satisifed (as far as I have Windows with multiple screens) that GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds() seems to return the same results for the default monitor. The benifit of the previous mention method, is it could be used to determine the "safe" bounds for any device

Credit to Java - Screen Size on a Mac



回答2:

frame.getContentPane().getHeight();

When you use this method, you get the height of the JFrame, not the screen. It also excludes the border heights.