4

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

我试过了:

MenuBar m = new MenuBar() {

      void paintComponent(Graphics g) {

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

但没什么

4

2 回答 2

6

好吧,首先,您所展示的不是JMenuBar,而是MenuBar,存在显着差异。尝试使用 aJMenuBar和 usesetBackground来改变背景颜色

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

    }

}
于 2012-08-09T23:20:49.493 回答
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 () );
        }
    } );

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

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

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

于 2012-08-10T13:28:22.030 回答