So I am trying to draw a label which contains an icon showing a circle. The circle will initially be filled red, and then depending on which of the 3 buttons I press, it will either change to green, blue, or red using repaint.
Here is what I have so far:
public class ColorChanger implements Icon {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame myFrame = new JFrame();
JButton redButton = new JButton("Red");
JButton greenButton = new JButton("Green");
JButton blueButton = new JButton("Blue");
Graphics g;
ColorChanger myCircle = new ColorChanger();
final JLabel myLabel = new JLabel(myCircle);
// myCircle.paintIcon(myFrame, g, 50, 50);
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 200;
myFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
myFrame.setLayout(new FlowLayout());
myFrame.add(redButton);
myFrame.add(greenButton);
myFrame.add(blueButton);
myFrame.add(myLabel);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
}
@Override
public int getIconWidth() {
// TODO Auto-generated method stub
return 10;
}
@Override
public int getIconHeight() {
// TODO Auto-generated method stub
return 10;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
// TODO Auto-generated method stub
Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Double circle = new Ellipse2D.Double(50, 50, 10, 10);
g2.setColor(Color.RED);
g2.fill(circle);
}
}
My issue is, I have no idea what to pass for the Graphics g in paintIcon. Is there a different way to do this? I appreciate any help with this.
The size of the icon is (10, 10). 50, is outside the bounds of the Icon. Painting is done relative to the icon so the ellipse should be:
Your ColorChanger class will need a
setColor(Color color)
method so that you can dynamically change the color to be painted. The paintIcon() method should then use this color.