Posts Tagged ‘ Swing

Setting a global default font for Swing applications

For my research, I am working on writing a Swing application for visualizing data. Part of this work is an exercise in human-computer interaction (HCI). To make this application more visually appeasing, we chose a font to apply to all Swing components. Originally, each component was initialized and then had

component.setFont(DEFAULT_FONT);

called on it. I did some searching on the Internet and realized this could all be avoided with a simple routine run before initializing the entire GUI:

private static void setDefaultFont() {
        Enumeration keys = UIManager.getDefaults().keys();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if (value instanceof javax.swing.plaf.FontUIResource) {
                UIManager.put(key, DEFAULT_FONT);
            }
        }
    }

This has worked extremely well and reduced our complexity cost for maintaining and enhancing the application.