javaswinglook-and-feeljmenujmenubar

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


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


Solution

  • Create a new class that extends JMenuBar:

    public class BackgroundMenuBar extends JMenuBar {
        Color bgColor=Color.WHITE;
    
        public void setColor(Color color) {
            bgColor=color;
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setColor(bgColor);
            g2d.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
    
        }
    }
    

    Now you use this class instead of JMenuBar and set the background color with setColor().