菜单项的显示不正确

时间:2016-05-26 20:16:34

标签: java swing

当我添加到我的JMenuItem新图标或ImageIcon时,文字会变成与图标相同的颜色。

Example Screenshot

我的代码:

JMenuButton red = new JMenuItem("Red", getIcon(Color.RED));

private Icon getIcon(Color color){
    return new Icon() {

        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
            Graphics2D g2 = (Graphics2D)g;
            g2.translate(x,y);
            g2.setPaint(color);
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            g2.fillOval( 0, 2, 10, 10 );
            g2.translate(-x,-y);
        }

        @Override
        public int getIconWidth() {
            return 14;
        }

        @Override
        public int getIconHeight() {
            return 14;
        }

    };
}

1 个答案:

答案 0 :(得分:2)

Graphics2D g2 = (Graphics2D)g;

不要只将Graphics对象转换为Graphics2D

您对Graphics2D对象所做的任何更改都将由Graphics对象保留。

而是创建一个可以临时自定义的单独Graphics对象:

Graphpics2D g2 = (Graphics2D)g.create();

//  do custom painting

g2.dispose();

现在,更改仅适用于自定义绘制代码。

相关问题