Change background and text color of JMenuBar and JMenu objects inside it

后端 未结 7 1702
孤街浪徒
孤街浪徒 2020-12-10 20:57

How can I set custom background color for JMenuBar and JMenu objects inside it? I tried .setBackgroundColor and it does not work!

7条回答
  •  情歌与酒
    2020-12-10 21:45

    The simplest way (I can think of) is to change the default values used by the UIManager. This will effect all the menu bars and menu items in the application though...

    enter image description here

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.EventQueue;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JPanel;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    public class TestMenuBar {
    
        public static void main(String[] args) {
            new TestMenuBar();
        }
    
        public TestMenuBar() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException ex) {
                    } catch (InstantiationException ex) {
                    } catch (IllegalAccessException ex) {
                    } catch (UnsupportedLookAndFeelException ex) {
                    }
    
                    UIManager.put("MenuBar.background", Color.RED);
                    UIManager.put("Menu.background", Color.GREEN);
                    UIManager.put("MenuItem.background", Color.MAGENTA);
    
                    JMenu mnu = new JMenu("Testing");
                    mnu.add("Menu Item 1");
                    mnu.add("Menu Item 2");
    
                    JMenuBar mb = new JMenuBar();
                    mb.add(mnu);
                    mb.add(new JMenu("Other"));
    
                    JFrame frame = new JFrame("Test");
                    frame.setJMenuBar(mb);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new JPanel());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
    
            });
        }
    
    }
    

提交回复
热议问题