【问题标题】:set JMenuBar's background color?设置 JMenuBar 的背景颜色?
【发布时间】:2012-08-07 06:21:07
【问题描述】:

比较直接,如何设置 JMenuBar 的背景颜色?

我试过了:

MenuBar m = new MenuBar() {

      void paintComponent(Graphics g) {

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

但没什么

【问题讨论】:

    标签: java swing colors background jmenubar


    【解决方案1】:

    首先,您显示的不是JMenuBar,而是MenuBar,存在显着差异。尝试使用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);
    
        }
    
    }
    

    【讨论】:

    • JMenuBar#setBackground 没有设置 JMenuBar 的背景颜色。
    • @Vulcan 好吧,你知道什么,每天都在学习 :)
    • @user1332495 请注意,它可能不适用于所有外观和感觉实现,我认为这就是 Vulcan 想说的
    • 它在我刚刚运行的测试中不起作用,但正确的是,我使用的是自定义 L&F。我会尽快删除反对票。对此感到抱歉。
    • BasicMenuUI 返回颜色数组、UImanager.put() 或 Painter
    【解决方案2】:

    使用 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。

    【讨论】:

    • wooohooo 直到现在我第二次看到 Xxx.class.getCanonicalName(),很棒的设计 +1
    • @mKorbel 谢谢,我真的不明白为什么大多数开发人员对类名进行硬编码(即使它们永远不会改变)。
    • 我试过你的第二种方法,但不知何故没有任何效果。我应该从哪里寻找问题?
    • @Czechnology 您可能没有在 UI 类中添加特殊的静态方法“createUI”,因此它根本不会影响 UI。这是创建自定义 UI 时最常见的错误。
    猜你喜欢
    • 1970-01-01
    • 2014-09-05
    • 2023-03-25
    • 2010-09-17
    • 2018-07-15
    • 2014-09-04
    • 2010-11-10
    • 2013-08-04
    • 1970-01-01
    相关资源
    最近更新 更多