当我向 JMenuItem
添加新图标或 ImageIcon
时,文本将变为与图标相同的颜色。
我的代码:
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;
}
};
}
最佳答案
Graphics2D g2 = (Graphics2D)g;
不要只是将 Graphics
对象转换为 Graphics2D
。
您对 Graphics2D
对象所做的任何更改都将由 Graphics
对象保留。
而是创建一个可以临时自定义的单独的 Graphics 对象:
Graphpics2D g2 = (Graphics2D)g.create();
// do custom painting
g2.dispose();
现在,更改将仅适用于自定义绘画代码。
关于java - 菜单项显示不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37470186/