Wednesday, October 10, 2007

Java Font vs Native Font

So, here is one more problem of Java being machine independent. Font size depicts by Java Application will not be same as of Native Application, like if we consider Windows OS, native applications are MS office, Notepad and many more. Conversion from the size in points into device pixels depends on device resolution as reported by the platform APIs. Java 2D defaults to assuming 72 dpi.Platform defaults vary like Mac OS: 72 dpi, Linux/Solaris: 96 dpi, Windows: 96 dpi/120 dpi.So whenever you write a code for java font, be carefully of it's inconsistency with native application.

Look at this code, how to manage the font size on a particular platform(pretty simple)

import java.awt.*;
import javax.swing.*;

public class TextSize extends JPanel {
public void paint(Graphics g) {
Font font = new Font("Arial", Font.PLAIN, 30);
g.drawString("Hello World", 25, 100);
Toolkit tk = Toolkit.getDefaultToolkit ();
int nativeResolution = tk.getScreenResolution();
final double javaResolution = 72.0; // java default is 72 dpi
Font font_new = new Font("Arial", Font.PLAIN, (int)Math.round(30.0*nativeResolution/javaResolution));
g.drawString("Hello World", 25, 150);
public static void main(String[] args) {
JFrame frame = new JFrame();
TextSize tx = new TextSize();

One can see the difference of Java and Native font size difference. The first "Hello World" is normal java code. Second " Hello World" is modified java code and third one is Native "Hello World". The staircase problem is also visible in Java Font, for removing that we can set ANTIALIAS_ON :-)


Amal said...

Interesting Sir.

Chan said...

It's very easy to understand. :-)

marathe said...

can u please tell a way to invoke native setting box for managing fonts and other system utilities??