I am trying to make JavaFX detect the screen resolution I'm on, either 1080p or 4k, so I can size/position my program accordingly.
I tried Screen.getPrimary().getDpi()
and it printed "96". Using Toolkit.getDefaultToolkit().getScreenResolution()
I got a result of "144". I have no idea which one is right or if there is a better way to do it.
Please help. Thanks.
You actually want to know the the screen size and not the pixel density. DPI is a measurement for Dots Per Inch.
In JavaFX you achieve this with the Screen class. As the user named jewelsea pointed out the visual bounds only return the values for the visual area of the selected screen. That means that you want to use screenObject.getVisualBounds()
for that and screenObject.getBounds()
for the actual screen sizes.
// full bounds
Rectangle2D bounds = Screen.getPrimary().getBounds();
bounds.getWidth(); // screens width
bounds.getHeight(); // screens height
// visual bounds
Rectangle2D visualBounds = Screen.getPrimary().getVisualBounds();
visualBounds.getWidth(); // screens usable width (no task bars etc.)
visualBounds.getHeight(); // screens usable height
In the code snippet the primary screen is used. You can also get other screens by using Screen.getScreens()
.