Change menu bar and menu items font

柔情痞子 提交于 2019-12-02 10:37:42
Frakcool

That's because there's not "menuBar.font" key in the UIManager class, it should be:

UIManager.put("MenuBar.font", f);

i.e. Caps are important or:

UIManager.put("MenuItem.font", f);

for each JMenuItem's font

Here's a list of these properties

Also related: Changing a JMenuBar's font


EDIT: Added mcve

I don't see where it's not working, if I run this code, it works fine for me

import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class UIManagerFontChangeExample {

    private JFrame frame;
    private JLabel label;
    private JMenuItem item1, item2;
    private JMenu menu;
    private JMenuBar bar;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Font f = new Font("sans-serif", Font.PLAIN, 12);
                UIManager.put("Menu.font", f);
                UIManager.put("MenuItem.font", f);
                UIManagerFontChangeExample example = new UIManagerFontChangeExample();
                example.createAndShowGui();
            }
        });
    }

    public void createAndShowGui() {
        frame = new JFrame("Font changing example");
        label = new JLabel("This is a label");
        bar = new JMenuBar();
        menu = new JMenu("Menu");
        item1 = new JMenuItem("Item1");
        item2 = new JMenuItem("Item2");

        menu.add(item1);
        menu.add(item2);
        bar.add(menu);

        frame.add(label);
        frame.setJMenuBar(bar);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

Before changing font:

After changing font:

The code I added above is called: Minimal, Complete and Verifiable Example, next time, please post a valid one, the same I did, so we can copy-paste, I didn't use an actionListener because the question isn't related to the actions, but the font. Or Icon because it's not related either, I did a full example code that you can copy-paste and see how it works, without modifying anything, that's what you were asked for.

For the MenuBar font you need to call:

UIManager.put("Menu.font", f);

And for the MenuItem

UIManager.put("MenuItem.font", f);

If you're updating UI Manager properties on the fly (such as after your GUI has appeared), you'll need to make a call to SwingUtilities.updateComponentTreeUI(Component) after you set the property UI Manager property. You'll want to pass in the highest level component you want to refresh (in this case, probably your top level Window or JFrame).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!