【问题标题】:JMenuBar and JMenu transparentJMenuBar 和 JMenu 透明
【发布时间】:2017-08-04 15:06:49
【问题描述】:

我在使用 Ntebeans 中的 JMenuBarJMenu 时遇到了一些问题。我只想知道我可以为其中的JMenuBarJMenu 对象设置自定义背景颜色吗?我尝试了setBackgroundColor() 方法,但它不起作用!我想设置白色或透明,我也试过了:

menubar.setBackground(Color.RED);
menu.setBackground(Color.yellow);
menubar.setOpaque(true);
menu.setOpaque(true);

还是这样

我想要一些这样的

我正在使用 Netbeans,当我设置预览时,JMenuBar 将背景设置为白色 JMenu Background White

但是当我运行程序时,还是一样 same color

【问题讨论】:

标签: java swing jmenu jmenubar


【解决方案1】:

它适用于我使用:

.setBackground(Color.RED) setOpaque(true)

【讨论】:

  • 但不适合我,我不知道该怎么做。我更新了添加更多图片的问题。
  • 你能把你的代码贴在你改变颜色/不透明的地方吗?可能是您在错误的组件上更改了其中一个?喜欢 JMenuItem 的 JMenu 吗?
  • 我在 ritgh 组件上改了:jMGeneral.setBackground(Color.red);jMGeneral.setOpaque(true);
  • 嗯,可能是它太大了,但我几乎所有的图形组件都使用带有插件“Window builder”的 Eclipse,它工作正常。可以考虑使用。否则,除了在错误的组件上执行 setBackground/opaque 之外,我看不出有什么问题。
  • 我正在使用 NetBeans,我尝试了一切,我确信我使用的是 rigth 组件,即使在 JMenu 的属性上,我设置 opaque = true 和 BackGround = #ffffff ...我搜索了很多示例,但我一无所获。
【解决方案2】:

您不需要将 JMenuBar 和 JMenuItem 的 opaque 设置为 true,因为它们默认具有 true 作为 opaque 值。但是,您已将 JMenu 的 opaque 显式设置为 true,因为它的默认值为 false。 这个简单的代码显示了 JMenuBar 和 JMenu 和 JMenuItem 的默认值:

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenu menu = new JMenu("My menu");
    menuBar.add(menu);

    JMenuItem item1 = new JMenuItem("My item");
    menu.add(item1);

    System.out.println(" " + menuBar.isOpaque() + ", " + menu.isOpaque() + ", " + item1.isOpaque());

您将在控制台中看到:真、假、真。因此,要更改 JMenu 的背景,您已将其 opaque 值设置为 true。

对于您想要的 gui,这里有一个简单的代码:

public class TutoMenuBar extends JFrame {

    public TutoMenuBar(String nameWindow) {
        super(nameWindow);
        initUI();
    }

    private void initUI() {

        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        JMenu testingJMenu = new JMenu("Testing");
        testingJMenu.setOpaque(true);
        testingJMenu.setBackground(Color.BLUE);
        menuBar.add(testingJMenu);

        JMenu otherJMenu = new JMenu("Other");
        otherJMenu.setOpaque(true);
        otherJMenu.setBackground(Color.GREEN);
        menuBar.add(otherJMenu);

        JMenuItem menu_item_1JMenuItem = new JMenuItem("Menu Item 1");
        menu_item_1JMenuItem.setBackground(new Color(251, 41, 255));
        testingJMenu.add(menu_item_1JMenuItem);

        JMenuItem menu_item_2JMenuItem = new JMenuItem("Menu Item 2");
        menu_item_2JMenuItem.setBackground(new Color(251, 41, 255));
        testingJMenu.add(menu_item_2JMenuItem);

        pack();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            TutoMenuBar test = new TutoMenuBar("Test");
            test.setVisible(true);
        });
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多