设置JMenuBar的背景颜色?

Pri*_*imm 4 java swing background colors jmenubar

相对简单,如何设置JMenuBar的背景颜色?

我试过了:

MenuBar m = new MenuBar() {

      void paintComponent(Graphics g) {

  Graphics2D g2 = (Graphics2D)g;
  g2.setBackground(Color.yellow);
  g2.fillRect(0, 0, getWidth(), getHeight());
}
Run Code Online (Sandbox Code Playgroud)

但没什么'

Mad*_*mer 6

嗯,首先,你所展示的不是a JMenuBar,它是MenuBar,有一个显着的差异.尝试使用a JMenuBar并使用setBackground更改背景颜色

来自Vulcan的反馈更新

好的,在setBackground不起作用的情况下,这将;)

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);

    }

}
Run Code Online (Sandbox Code Playgroud)


Mik*_*rin 6

使用MadProgrammer的方法,您将获得两次绘制的菜单栏背景 - 一次通过UI(例如,它可能是Windows上的渐变,需要一些时间来绘制),一次通过paintComponent方法中的代码(旧背景的顶部).

最好用您自己的基于BasicMenuBarUI替换菜单UI:

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

您还可以为所有菜单栏全局设置该UI,这样您每次创建菜单栏时都不需要使用特定组件:

UIManager.put ( "MenuBarUI", MyMenuBarUI.class.getCanonicalName () );
Run Code Online (Sandbox Code Playgroud)

这里的MyMenuBarUI类是所有菜单栏的特定UI.