Reputation: 155
When I add to my JMenuItem
new Icon or ImageIcon
, then the text becomes the same color as the icon.
My code:
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;
}
};
}
Upvotes: 1
Views: 78
Reputation: 324157
Graphics2D g2 = (Graphics2D)g;
Don't just cast the Graphics
object to a Graphics2D
.
Any changes you make to the Graphics2D
object will be retained by the Graphics
object.
Instead create a separate Graphics object that you can temporarily customize:
Graphpics2D g2 = (Graphics2D)g.create();
// do custom painting
g2.dispose();
Now the changes will only apply to the custom painting code.
Upvotes: 2