Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the default font size in the Swing GTK LookAndFeel?

Is there a way to change the default font size in the Swing GTK LaF?

The GTK LaF seems to assume 72dpi, so all the fonts are only 3/4 of the size they should be when using a 96dpi screen. See this Fedora bug for details. I'd like to find a workaround in the meantime, while I wait for the fix.

I've already tried resetting the font size via UIDefaults, as recommended here, for example, but (as also noted there) the GTK LaF appears to ignore this.

I could build a widget factory that would also set the desired font size for creating all of my Swing widgets, but that's going to be massively invasive, so I'd like to avoid that route if there's any other way.

Edit: The following doesn't work:

public class GTKLaF extends com.sun.java.swing.plaf.gtk.GTKLookAndFeel {
  @Override
  public UIDefaults getDefaults() {
    final float scale = 3f;

    final UIDefaults defaults = super.getDefaults(); 

    final Map<Object,Object> changes = new HashMap<Object,Object>();

    for (Map.Entry<Object,Object> e : defaults.entrySet()) {
      final Object key = e.getKey();
      final Object val = e.getValue();

      if (val instanceof FontUIResource) {
        final FontUIResource ores = (FontUIResource) val;
        final FontUIResource nres =
          new FontUIResource(ores.deriveFont(ores.getSize2D()*scale));
        changes.put(key, nres);
        System.out.println(key + " = " + nres);
      } 
      else if (val instanceof Font) {
        final Font ofont = (Font) val;
        final Font nfont = ofont.deriveFont(ofont.getSize2D()*scale);
        changes.put(key, nfont);
        System.out.println(key + " = " + nfont);
      }
    }

    defaults.putAll(changes);

    return defaults;
  }
}

You might think this would print at least a dozen key-value pairs, but it prints only one: TitledBorder.font. Apparently the other font properties are not supplied by the GTLLookAndFeel, but come from someplace else!

like image 928
uckelman Avatar asked Nov 05 '22 08:11

uckelman


1 Answers

My suggestion is to create your own subclass of GTKLookAndFeel and use that.

In your subclass, I'd probably override getDefaults(). In your getDefaults() you can get the UIDefaults that GTKLookAndFeel was going to return and adjust them if necessary. (By wrapping or subclassing them and overriding the UIDefaults.getFont methods.)

Get the current DPI with

int dpi = Toolkit.getDefaultToolkit().getScreenResolution();

and if it's not 72 you can change the font size accordingly.

Edit: the link you posted doesn't work, I believe because GTKLookAndFeel overrides the methods involved and doesn't let any defaults from its ancestors to pass through. Overriding it in turn should allow you to circumvent that problem.

like image 113
Brad Mace Avatar answered Nov 09 '22 04:11

Brad Mace