简体   繁体   中英

How to get the width and height of current monitor in java

how to get width and height of screen of current monitor in multimonitor scenarios in java.

GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    int width = gd.getDisplayMode().getWidth();
    int height = gd.getDisplayMode().getHeight();

This piece of code gives the width and height of same monitor even if I run in other monitor.

How do you get the width and height of current monitor. Please help.

It depends on what you mean by the current screen. If it is the screen where the mouse cursor is, you can get the device with:

GraphicsDevice gd = MouseInfo.getPointerInfo().getDevice();

On the other hand, if you need the device where a window is located, use:

GraphicsDevice gd = frame.getGraphicsConfiguration().getDevice();

From these you can obtain the dimensions:

int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();

In addition to the comment, you may obtain all available monitors:

GraphicsDevice.getLocalGraphicsEnvironment().getScreenDevices()

and know them resolutions

Try:

GraphicsDevice gd[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();

Then you'll have all your monitor in the array.

Now get width and height:

int width = gd[n].getDisplayMode().getWidth();
int height = gd[n].getDisplayMode().getHeight();

You can get screen dimensions using Toolkit as follows:

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

For multi-screen try following:

GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM