简体   繁体   中英

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.

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.

// 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.


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. 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.

I'd suggest to use Swing components instead: they provide much more flexibility:

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

You should have no problems integrating Swing components with existing AWT components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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