在 JMenuItem 中设置图标使菜单文本匹配图标颜色 [英] Setting icon in JMenuItem makes menu text match icon color

查看:37
本文介绍了在 JMenuItem 中设置图标使菜单文本匹配图标颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

添加菜单项时(无论是在我下面的示例中进行硬编码还是使用 Action),图标的颜色会导致菜单项文本的颜色发生变化.这很奇怪,如果图标为白色或非常浅,可能会导致菜单项不可读.我如何关闭它?在菜单项上调用 setForeground(Color.black) 不起作用.

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);
    }
}

这发生在我的应用程序中的 Mac Aqua L&F 和 Windows 中.SSCCE 在 Mac 上也会导致这种情况,但奇怪的是,在 Windows 中不会.(Windows 中还有其他 UI 差异:SSCCE 在图标和文本之间有一个垂直分隔符;我的应用程序没有.)

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

推荐答案

听起来像 Graphics 实例被重用于图标和文本.在paintIcon 末尾添加g.setColor(Color.BLACK) 会发生什么?

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?

我会说这是 L&F 中的一个错误.也许最好将图形的原始颜色存储起来,并在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.

这篇关于在 JMenuItem 中设置图标使菜单文本匹配图标颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆