JMenu submenu little arrow icon indicator

2020-05-06 13:50发布

问题:

Does anyone know how to control the display of the tiny little arrow that appears on submenus of JMenu?

Can I change it? Can I disable it? Can I move it?

Also, I notice that this arrow doesn't appear on top level JMenus only when they are submenus of other JMenu. This inconsistency annoys me since I have a mix of JMenuItem and JMenu attached to the root of my JMenuBar and so I wish it would always indicate it. Anyway to do this as well?

thanks!

回答1:

Take a look at the Menu.arrowIcon UI property

(Thanks to AndrewThompson for the test code).

Doining this will effect ALL the menus created AFTER you apply the modifications.

So after you init Look and Feel and before you create any menus call UIManager.getLookAndFeelDefaults().put("Menu.arrowIcon", null);

I'd just like to say I think this is a terrible idea and would highly discourage you from doing it.



回答2:

this arrow doesn't appear on top level JMenus only when they are submenus of other JMenu.

It seem (monotonously) consistent in its appearance using Metal here.

import javax.swing.*;

public class MenuArrows {

    MenuArrows() {
        JMenuBar mb = new JMenuBar();

        JMenu root1 = new JMenu("Root Menu 1"); 
        JMenu root2 = new JMenu("Root Menu 2"); 

        addSubMenus(root1, 5);
        addSubMenus(root2, 3);

        mb.add(root1);
        mb.add(root2);

        JOptionPane.showMessageDialog(null, mb);
    }

    public void addSubMenus(JMenu parent, int number) {
        for (int i=1; i<=number; i++) {
            JMenu menu = new JMenu("Sub Menu " + i);
            parent.add(menu);

            addSubMenus(menu, number-1);
            addMenuItems(menu, number);
        }
    }

    public void addMenuItems(JMenu parent, int number) {
        for(int i=1; i<=number; i++) {
            parent.add(new JMenuItem("Item " + i));
        }
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                new MenuArrows();
            }
        };
        SwingUtilities.invokeLater(r);
    }
}