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
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class TestClass
{
public static void main(String[] args)
{
JFrame LightVisible = new JFrame();
LightVisible.setSize(400,400);
LightVisible.setTitle("Traffic Lights");
LightVisible.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TrafficLight trafficViewerOne = new TrafficLight();
JOptionPane.showMessageDialog(null,"Ready!");
LightVisible.add(trafficViewerOne);
LightVisible.setVisible(true);
JOptionPane.showMessageDialog(null,"Set!");
trafficViewerOne.setColor( Color.YELLOW );
JOptionPane.showMessageDialog(null,"Go!");
trafficViewerOne.setColor( Color.GREEN );
}
}
class TrafficLight extends JComponent
{
private Color lightColor;
public TrafficLight()
{
// 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);
g2.setColor(Color.WHITE);
g2.fill(box);
Ellipse2D.Double lightRing = new Ellipse2D.Double(35,75,200,200);
g2.setColor( lightColor );
g2.draw(lightRing);
g2.fill(lightRing);
}
public void setColor(Color newLightColor)
{
lightColor = newLightColor;
repaint();
}
}