使用 AWT 组件更改 Java 中 MenuBar、Menu 和 MenuItem 的颜色

Change Color of MenuBar, Menu, and MenuItem in Java using the AWT Components

我一直在四处寻找,但我还没有找到关于是否可以以及如何更改背景、文本、前景、选择和文本选择颜色的答案。 MenuBar、Menu 和 MenuItem AWT 组件。

到目前为止,我已经尝试了以下解决方案,但都没有影响任何与菜单相关的组件的任何颜色。第一个解决方案只是尝试获取组件并更改颜色,第二个解决方案尝试通过 UIManager 更改它。

// Just an example of what I did, this is not from the code I'm working with.    
MenuBar bar = new MenuBar();
Menu menu = new Menu();
MenuItem item = new MenuItem();

bar.getAccessibleContext().getAccessibleComponent().setBackground(Color.RED);
bar.getAccessibleContext().getAccessibleComponent().setForeground(Color.BLUE);

menu.getAccessibleContext().getAccessibleComponent().setBackground(Color.RED);
menu.getAccessibleContext().getAccessibleComponent().setForeground(Color.BLUE);

item.getAccessibleContext().getAccessibleComponent().setBackground(Color.RED);
item.getAccessibleContext().getAccessibleComponent().setForeground(Color.BLUE);

--

UIManager.put("MenuItem.background", Color.RED);
UIManager.put("MenuItem.foreground", Color.BLUE);

我以前没有使用过 AWT 组件,如果答案很明显,我很抱歉。


更新:

如果您希望能够轻松更改组件颜色,那么使用 AWT 组件似乎不是一个好主意。我将重构我的代码以消除尽可能多的 AWT 组件以支持 Swing 组件,我建议任何阅读本文的人都尽可能这样做。

我建议改用 Swing 组件:它们提供了更多的灵活性:

JMenuBar bar = new JMenuBar();
bar.setBackground(Color.RED);
bar.setForeground(Color.BLUE);

将 Swing 组件与现有 AWT 组件集成应该没有问题。