Search code examples
javaswinguser-interfacefontsnimbus

Java: Altering UI fonts (Nimbus) doesn't work!


I'm referring to this Nimbus reference.

I tried to set global Font to be slightly larger:

UIManager.put("defaultFont", new Font(Font.SANS_SERIF, 0, 16));

...works only for the menu but nothing else (buttons, labels).

I tried to change labels and buttons fonts with

UIManager.put("Button.font", new Font(Font.SANS_SERIF, 0, 16));
UIManager.put("Label.font", new Font(Font.SANS_SERIF, 0, 16));

but the font remains.

The only thing that worked for me was deriving a font:

someButton.setFont(someButton.getFont().deriveFont(16f));

But this is not an option, since this must be done for each element manually.

Note, that deriving a font for UIManager doesn't work either:

UIManager.put("Label.font",
    UIManager.getFont("Label.font").deriveFont(16f));

I tested everything under Linux and Windows: same behavior.

I just can't understand how an API can be so messy. If a method is called setFont(..) then I expect it to set the font. If this method fails to set the font in any thinkable circumstances, then it should be deprecated.

EDIT:
The problem not only applies to Nimbus, but also to the default LAF.


Solution

  • This works with JDK6 and JDK7. Copy+paste and have fun ;)

    Note: for JDK6, change
    javax.swing.plaf.nimbus to
    com.​sun.​java.​swing.​plaf.​nimbus.

    Code

    import java.awt.*;
    import java.lang.reflect.*;
    import javax.swing.*;
    import javax.swing.plaf.nimbus.*;
    
    public class Main {
    
     public static void main(String[] args)
       throws InterruptedException, InvocationTargetException {
    
      SwingUtilities.invokeAndWait(new Runnable() {
    
       @Override
       public void run() {
        try {
         UIManager.setLookAndFeel(new NimbusLookAndFeel() {
    
          @Override
          public UIDefaults getDefaults() {
           UIDefaults ret = super.getDefaults();
           ret.put("defaultFont",
             new Font(Font.MONOSPACED, Font.BOLD, 16)); // supersize me
           return ret;
          }
    
         });
    
         new JFrame("Hello") {
    
          {
           setDefaultCloseOperation(EXIT_ON_CLOSE);
           setLayout(new FlowLayout(FlowLayout.LEFT));
    
           setSize(500, 500);
           setLocationRelativeTo(null);
    
           add(new JLabel("someLabel 1"));
           add(new JButton("someButton 1"));
           add(new JLabel("someLabel 2"));
           add(new JButton("someButton 2"));
    
           setVisible(true);
          }
    
         };     
        } catch (Exception ex) {
         throw new Error(ex);
        }
       }
    
      });
     }
    
    }