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

后端 未结 6 1486
傲寒
傲寒 2020-12-30 12:21

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,         


        
6条回答
  •  余生分开走
    2020-12-30 13:11

    Java LAF API is a little bit clumsy, but there is nothing better than check the source code to get your answers.

    Note that MetalLookAndFeel and Nimbus are different implementations and the properties for each one doesn't have to be the same.

    The following examples use the MetalLookAndFeel.

    package com.stackoverflow.laf.font;
    
    import java.awt.Font;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    
    public class SetFontExample {
    
      public static void main(String[] args) {
    
        SwingUtilities.invokeLater(new Runnable() {
          @Override public void run() {
            UIManager.put("Label.font", new Font(Font.SANS_SERIF, 0, 20));
            try {
              UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
            } catch (Exception e) {
              e.printStackTrace();
            }
    
            JFrame frame = new JFrame("Set font example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new JLabel("Font test"));
            frame.pack();
            frame.setVisible(true);
          }
        });
      }
    }
    

    This works because the property "Label.font" exists on Metal and it uses that property correctly.

    You you can check it this way:

    package com.stackoverflow.laf;
    
    import javax.swing.SwingUtilities;
    import javax.swing.UIDefaults;
    import javax.swing.UIManager;
    
    public class ListLAFUIDefaults {
    
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override public void run() {
            try {
              // Choose LAF
              UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
            } catch (Exception e) {
              e.printStackTrace();
            }
            UIDefaults defaults = UIManager.getLookAndFeel().getDefaults();
            System.out.println(defaults);
    
            // Check a property
            String propertyKey = "defaultFont";
            System.out.println(UIManager.getLookAndFeel().getName() +
                (defaults.containsKey(propertyKey) ? " contains " : " doesn't contain ") +
                "property " + propertyKey);
          }
        });
      }
    }
    

提交回复
热议问题