Traffic lights don't go red, yellow, green, but I'll assume that the requirements are dictated by the assignment.
You have all of the necessary elements, some of them unused, others used incorrectly. I'm not going to show you anything new by talking you through each of the necessary changes, so I'll mention the important changes and then post your corrected code:
paintComponent(() should begin with a call to the super's paintComponent() method
NEVER, NEVER, NEVER call repaint from the paintComponent() method. Doing so creates an infinite loop and indicates you don't understand Swing's painting mechanism. You can learn more about it in Oracle's Custom Painting lesson.
Use the setColor() method between dialog boxes to change the light's color. (Should be named setLightColor().)
You might want to move the first dialog to after the setVisible() statement and then alternate change color / new dialog, but that's up to you.
Here's the working code:
//Traffic Light viewer
//Import JComponent Graphics, Graphic2D, Color
public class TestClass
public static void main(String args)
JFrame LightVisible = new JFrame();
TrafficLight trafficViewerOne = new TrafficLight();
trafficViewerOne.setColor( Color.YELLOW );
trafficViewerOne.setColor( Color.GREEN );
class TrafficLight extends JComponent
private Color lightColor;
// set initial color to green
lightColor = Color.RED;
public void paintComponent(Graphics g)
// always begin the paintComponent() method with:
super.paintComponent( g );
//convert g to graphics 2d and use to draw ellipse for circle.
//set color to lightColor
Graphics2D g2 = (Graphics2D) g;
Rectangle box = new Rectangle(0,0,300,400);
Ellipse2D.Double lightRing = new Ellipse2D.Double(35,75,200,200);
g2.setColor( lightColor );
public void setColor(Color newLightColor)
lightColor = newLightColor;