Class HighLite GraphicsEnvironment

As a Java developer, every once in a while I need write code that lists all the available fonts or requires the screen dimensions for some calculation. To do this sort of work I often use the java.awt.GraphicsEnvironment class. To get started let me demonstrate how to get an array of all the available fonts.

[source:java]
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts = ge.getAllFonts();
[/source]

If you want to work with the available font families you can use the getAvailableFontFamilyNames method.

[source:java]
String[] fontFamilies = ge.getAvailableFontFamilyNames();
[/source]

When working with Swing pop up dialogs it is a good idea to make sure they are not clip by the screen size. When you pop up a dialog you want it to fit completely inside the screen. To do this sort of simple calculation you need to know the screen height and with of your display, which can be done with the getMaximumWindowBounds method of the GraphicsEnvironment class.

[source:java]
// Screen height
int height = ge.getMaximumWindowBounds().height;
// Screen width
int width = ge.getMaximumWindowBounds().width;

// Your algorithm goes here…
[/source]

With the above information, for example, you can make sure that a dialog’s location plus its size does not exceed the screen height.

From my experience, a typical Java developer is illuminated with two 19 inch LCD monitors. If you are working with more than one monitor you may want to use code similar to the following.

[source:java]
// All available screen devices
GraphicsDevice[] gda = ge.getScreenDevices();
for(int i=0; i < gda.length; i++) { DisplayMode dm = gda[i].getDisplayMode(); int height = dm.getHeight(); int width = dm.getWidth(); // Do something for each display height/width... } [/source] This is part of the Class HighLite Series, which intends to highlight some interesting code and classes available from the JDK.

Technorati Tags: , , , , , ,


Leave a Reply