Question

When adding a menu item (whether hard-coded as in my example below or with an Action), the color of the icon causes the color of the text of the menu item to change. This is strange and, in the case of a white or very light icon, can cause the menu item to be unreadable. How do I turn this off? Calling setForeground(Color.black) on the menu item does not work.

SSCCE:

import javax.swing.*;
import java.awt.*;

public class Test extends JFrame
{
    public Test()
    {
        JMenuBar bar = new JMenuBar();

        JMenu menu = new JMenu("menu");

        menu.add(new JMenuItem("crap name", new Icon(){
            @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                g.setColor(Color.blue);
                ((Graphics2D)g).fill3DRect(0, 0, 8, 8, true);
            }
            @Override
            public int getIconWidth() {
                return 8;
            }
            @Override
            public int getIconHeight() {
                return 8;
            }
        }));

        bar.add(menu);

        setJMenuBar(bar);
    }

    public static void main(String[] args)
    {
        Test app = new Test();
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        app.setVisible(true);
    }
}

EDIT: This occurs in the Mac Aqua L&F and in Windows in my app. The SSCCE also causes this on the Mac, but not, oddly enough, in Windows. (There are other UI differences in Windows: the SSCCE has a vertical separator between the icon and the text; my app doesn't.)

Was it helpful?

Solution

It sounds like the Graphics instance is being reused for both the icon and the text. What happens when you add g.setColor(Color.BLACK) at the end of paintIcon?

I would say that this is a bug in the L&F. Maybe it's best to store the graphics' original color and restore it at the end of paintIcon.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top