user2947476 user2947476 - 1 year ago 150
Java Question

Render a Java AWT canvas to fit screen

I am currently making a game using Java's AWT library
The game is rendered at 1080p, and works well on 1080p screens, but goes over the edge of a 720p monitor, and leaves lots of empty space on a 4k monitor. I want to shrink or enlarge the canvas depending on the screen size to fit the screen.

If you are having trouble with the AWT library for games I suggest using LWJGL/OpenGL instead, as it is purpose-built and much faster than AWT, as well as having much higher functionality. The syntax for OpenGL is more complex, however, it's not too difficult to create a simple interface that complies with less complex needs. It should also be noted that although it can be complex to install, LWJGL comes with lots of the background work, such as game speed and screen scaling built in. The path of least resistance is not always the best one.

Answer Source

The answer is, you can make it full screen using ToolKit.getScreenSize / getScreenResolution. Then, what you want to do is add default values for size and resolution that look nice on your 1080p screen, add ComponentListener to the (J)Frame or its ContentPane, and implement componentResized. Then rescale the size everything in your game using the ratio of your default screen size and your default resolution.

Dimension DEFAULT_SIZE = ...;
Dimension actualScreenSize = Toolkit.getToolkit().getScreenSize();
int actualResolution = Toolkit.getToolkit().getScreenResolution();
AffineTransform at = AffineTransform.getScaleInstance(...,...);
//Apply scaling to your Components and Shapes 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download