Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set JMenuBar's background color?

relatively straight-forward, how can I set the background color of a JMenuBar?

ive tried:

MenuBar m = new MenuBar() {

      void paintComponent(Graphics g) {

  Graphics2D g2 = (Graphics2D)g;
  g2.setBackground(Color.yellow);
  g2.fillRect(0, 0, getWidth(), getHeight());
}

but nothin'

like image 731
Primm Avatar asked Dec 16 '22 20:12

Primm


2 Answers

Well, to start with, what you've shown is not a JMenuBar, it's MenuBar, there's a significant difference. Try using a JMenuBarand use setBackground to change the background color

Updated from feedback from Vulcan

Okay, in the cases where setBackground doesn't work, this will ;)

public class MyMenuBar extends JMenuBar {

    @Override
    protected void paintComponent(Graphics g) {

        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.RED);
        g2d.fillRect(0, 0, getWidth() - 1, getHeight() - 1);

    }

}
like image 140
MadProgrammer Avatar answered Dec 27 '22 22:12

MadProgrammer


With MadProgrammer's approach you will get menubar background painted twice - once by the UI (it could be gradient on Windows for example, which takes some time to paint) and once by your code in paintComponent method (atop of the old background).

Better replace menubar UI by your own one based on BasicMenuBarUI:

    menuBar.setUI ( new BasicMenuBarUI ()
    {
        public void paint ( Graphics g, JComponent c )
        {
            g.setColor ( Color.RED );
            g.fillRect ( 0, 0, c.getWidth (), c.getHeight () );
        }
    } );

You can also set that UI globally for all menubars so that you don't need to use your specific component each time you create menubar:

UIManager.put ( "MenuBarUI", MyMenuBarUI.class.getCanonicalName () );

MyMenuBarUI class here is your specific UI for all menubars.

like image 40
Mikle Garin Avatar answered Dec 27 '22 23:12

Mikle Garin