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'
Well, to start with, what you've shown is not a JMenuBar
, it's MenuBar
, there's a significant difference. Try using a JMenuBar
and 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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With