Emd4600 Emd4600 - 9 days ago 7
Java Question

Swing fonts look smaller than they should

I'm working in a Swing program that needs to display text of a given font size. But I've noticed that in Swing, the text looks a lot smaller than it should be. The text is barely readable at small font sizes compared to, for example, Microsoft Word.

Both Swing and Microsoft Word are using Arial, 8. The difference is clear.
enter image description here

For those wanting to try, here's a small example:

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);

JLabel label = new JLabel("This is my test text which should look bigger");
label.setFont(new Font("Arial", Font.PLAIN, 8));

frame.add(label);

frame.setVisible(true);
}


Anyone has any idea of what could be going on?

Answer

in the java Documentations a Font should get the size in pt but it seems to uses px instead.

So your Text is not 8pt (like in word or libre office, ...) its 8 pixels height. You can convert the pt to px (8pt = ~ 10px)

enter image description here

The exact formula for conversion is not as simple, because its device specific, but you can use (correct for ppi = 96):

pt = px*0.75
px = pt/0.75

This formula is not accurate, but as you can see in my test image: 10/0.75 = = 7.5pt (Size 10 is nearest to the word text)

If you want it as accurate as possible, you can calculate it for your device: a pt is defined as 1/72 in (see wikipedia) so the formula is:

px = pt / (72 / ppi); //ppi = points per inch

In java you can do it as this:

public int pointToPixel(float pt){
   int ppi = Toolkit.getDefaultToolkit().getScreenResolution();
   return pt / (72 / ppi);
}