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

5.7k views Asked by At

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.

1

There are 1 answers

3
Tagir Valeev On BEST ANSWER

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.