简体   繁体   English

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

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

I've been searching around for a bit, but I haven't found an answer as to whether or not it's possible to and how to change the background, text, foreground, selection, and text selection colors of the MenuBar, Menu, and MenuItem AWT components. 我一直在搜索,但是我没有找到关于是否可以更改菜单栏,菜单和菜单栏的背景,文本,前景,选择和文本选择颜色的答案。 MenuItem AWT组件。

So-far I've tried the following solutions, but neither affect any of the colors of any of the Menu-related components. 到目前为止,我已经尝试了以下解决方案,但是都不会影响任何与菜单相关的组件的颜色。 The first solution just attempts to grab the component and change the color and the second tries to change it through the UIManager. 第一个解决方案仅尝试获取组件并更改颜色,第二个解决方案尝试通过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);

I haven't worked much with the AWT components before, so sorry if the answer is obvious. 之前我没有对AWT组件进行过多的工作,如果答案很明显,请对不起。


Update: 更新:

It seems as if using the AWT components is just a bad idea if you're looking to be able to easily change the component colors. 如果您希望能够轻松更改组件颜色,则似乎使用AWT组件似乎不是一个好主意。 I'll be refactoring my code to eliminate as many AWT components in favour of the Swing components and I suggest anyone reading this do the same if at all possible. 我将重构我的代码,以消除尽可能多的AWT组件,而使用Swing组件,并且建议阅读此文档的人尽可能地做同样的事情。

I'd suggest to use Swing components instead: they provide much more flexibility: 我建议改用Swing组件:它们提供了更大的灵活性:

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

You should have no problems integrating Swing components with existing AWT components. 将Swing组件与现有的AWT组件集成在一起应该没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM