Search code examples
javaswinglanguage-features

Java Upside Down Text - Bug or Feature?


While playing around with the Java font class and Swing, I set the font size to a negative value.

I discovered that this makes the text be drawn upside down. Is this a bug or a feature? Can anyone explain why this behavior happens?

Try it out:

import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class UpsideDown extends JFrame{

    public UpsideDown(){
        setSize(500,500);
        setContentPane(new Panel());
        setVisible(true);
    }

    public class Panel extends JPanel{
        public void paintComponent(Graphics g){
            Font f = new Font("Sans-Serif", Font.PLAIN, -50);
            g.setFont(f);
            g.drawString("Upside Down", 400, 100);
        }
    }

    public static void main(String args[]){
        new UpsideDown();
    }
}

Upside Down


Solution

  • Seems like this is happening:

    1. Swing draws your font's height downwards, because it multiplies the font size with the glyph height of the font. -50 * glyph_height is negative -> drawing downwards instead of upwards.
    2. It also draws the glyph's (the letter's) width to the left, again because it multiplies your font size with the glyph width specified by the font.