Thursday, June 21, 2007

Fullscreen & ScreenModes in Java Games

Setting up a JFrame in Fullscreen

To make a JFrame fullscreen you need to first get a valid graphics device which can be obtained from the GraphicsEnvironment object in java.awt package. Here is a quick example call,
GraphicsDevice gd =
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();

The GraphicsDevice object has a method called setFullScreenWindow it has one parameter which is a Window object and JFrame is a subclass of Window so you can pass it as an argument to the method.


Changing Display Modes

Ok so now we have a window that takes up the whole screen but what if you want to change the Screen Resolution to work best with your game. No problem!

The GraphicsDevice object has another method for doing just that. The name of the method is setDisplayMode that takes a single parameter. The parameter is a DisplayMode object. An example creation of a DisplayMode object is shown below:

DisplayMode dm = new DisplayMode(640,480,32,60);

When passed to the GraphicsDevice.setDisplayMode will attempt to change your current default monitors screen resolution to 640 pizels in width by 480 pixels in height with 32 bits of space for storing the color of each pixel on screen and a screen refresh rate of 60 hertz.

Warnings:
1) You cannot change the DisplayMode without a fullscreened window.
2) Changing the DisplayMode to something that is not supported by your monitor or display can cause an exception to be thrown.

Notes:
To get a full listing of supported DisplayModes you can use the GraphicsDevice.getDisplayModes() method which will return an array of valid DisplayMode objects. (good for settings option in Games)

Stripping The JFrame Decorations

Well now you can make a fullscreen window but what about that border thats no good for games. All you need to do is the following:

this.setUndecorated(true);
This call is made on any java.awt.Frame object.

How to Escape

Just add a keyListener to the frame. This may be a problem later on if you include other awt or swing components.

Example: Seeing is Believing

2 comments:

Varacx said...

Are these good references even though they were made in 2007?

Nick said...

Good catch, you are right the referenced javadoc links are bad now. Silly Oracle buying Java. I will go through all the posts and update the javadoc references to be more oracle friendly. Thanks for pointing that out.

Post a Comment