Friday, June 8, 2007

FONTS

FONTS

to work with fonts, two classes are worth noting, the GraphicsEnvironment and Font classes which are both in the java.awt package.

GraphicsEnvironment: this class describes a collection of GraphicsDevices and font objects that are available to a java application on a particular platform and note that the resources might be local or remote. GraphicsDevices might be screens, printers or image buffers. Each GraphicsDevice has a number of Graphicsconfiguration objects associated with it that specifies configuration usage for different GraphicsDevices.

Font: this represents a class for rendring text in a visible way. A font provides information needed to map sequence of characters to sequence of glyphs and to render a sequence of glyphs as Graphics on component classes.

we can retrieve font related properties from a local or remote machine using the GraphicsEnvironment and font classes working together.

Here is a code that demonstrates the fonts available on my windows xp machine:

package tests;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;

public class Property extends JPanel{

static JButton jButton1 = new JButton(" ");
static JTextArea jText;
/** Creates a new instance of Property */
public Property() {
jButton1 = new JButton("click me");
add(jButton1);
jText = new JTextArea(" ", 10, 20);
add(jText);
GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = genv.getAvailableFontFamilyNames();
for (int i=0; i simplyText(fontNames[i]);
}
}

private static void dButton(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Property");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Property nProp = new Property();
nProp.setOpaque(true);
frame.setContentPane(nProp);
frame.pack();
frame.setVisible(true);
}

public static void simplyText(String txt){
jText.append(txt+"\n");

}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
dButton();
}
});
}
}

Although we can use the classic getXX() accessor methods for font objects note that to set them we have to derive fonts using an overloaded deriveFont() method.

No comments: