How do I use anti-aliased fonts in Java?
Anti-aliasing is a graphical technique used to smooth jagged edges. Although it takes longer to draw things when anti-aliasing is used, the result is usually well worth the extra processing power required. Anti-aliasing is especially useful with text — anti-aliased fonts are much cleaner, better-looking, and more readable.
In Java, there are two ways to enable font anti-aliasing with Swing. Prior to Java 1.5, the simplest way to enable anti-aliasing of fonts is to use the SmoothMetal look-and-feel. SmoothMetal adds anti-aliasing support to the standard look-and-feels that ship with Java. A few changes to your application might be required, but it’s mostly transparent.
From Java 1.5 and on, however, it’s even simpler. All you do is set a system property, swing.aatext, to ‘true’ at the start of your application. Here’s some sample code that shows how it’s done:
public static void start() {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
System.setProperty( “swing.aatext”, “true” );
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch( Throwable e ){
// oops
}
new MyFrame( app, options ).setVisible( true );
}
});
}
Just be sure to set the swing.aatext property before any Swing calls are made.
Comments
5 Responses to “How do I use anti-aliased fonts in Java?”
Leave a Reply
I don’t think that this property is supported after JDK 5.0. Since JDK 6.0, the officially supported way is described at [1]
[1] http://weblogs.java.net/blog/chet/archive/2007/01/font_hints_for.html
Googling around you can see this is an undocumented property used in Sun’s jvm. Not even they support it anymore….see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6391267
Some info on subpixel font rendering stuff can be found at https://java.sun.com/javase/6/docs/api/java/awt/doc-files/DesktopProperties.html and http://weblogs.java.net/blog/chet/archive/2005/06/phils_font_fixe.html
It may not be officially supported anymore, but it still works as far as I can tell. I have a Java 5 application that looks a LOT better with these settings, no matter which JRE (5 or 6) it’s running under.
Under JDK 6.0, the core look-and-feels respect the desktop anti-alias settings. Try commenting the line that sets the swing.aatext property and run your app once again under JDK 6.0 with Metal, Windows or GTK look-and-feels.
Kirill
But I need to support Java 5, so for now the property’s staying in.