import javax.swing.*; import java.awt.*; import java.awt.Graphics; import java.awt.event.*; public class TrafficLight extends JFrame { private NewLabel lights = new NewLabel(); private JRadioButton red, yellow, green; public TrafficLight() { JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(1,3)); add(lights, BorderLayout.CENTER); add(p1, BorderLayout.SOUTH); p1.add(red = new JRadioButton("Red")); p1.add(yellow = new JRadioButton("Yellow")); p1.add(green = new JRadioButton("Green")); //Button Group ButtonGroup group = new ButtonGroup(); group.add(red); group.add(yellow); group.add(green); } class LightListener implements ActionListener { public void actionPerformed (ActionEvent e) { red.addActionListener(new LightListener()); green.addActionListener(new LightListener()); yellow.addActionListener(new LightListener()); if (e.getSource() == red) System.out.println("red"); else if (e.getSource() == yellow) System.out.println("yellow"); else if (e.getSource() == green) System.out.println("green"); } } public static void main(String[] args) { TrafficLight frame = new TrafficLight(); frame.setTitle("TrafficLight"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200, 250); frame.setVisible(true); } class NewLabel extends JPanel { protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawRect(10,10,50,150); g.drawOval(10,10,50,50); g.drawOval(10,60,50,50); g.drawOval(10,110,50,50); } } }
I can't make it so that when you click the radio button it repaints the circle the appropriate color. In this case, the colors of a traffic light.
If the source is red: It needs to paint the top circle red
If the source is yellow: It needs to paint the center circle yellow
If the source is red: It needs " " " red...
I'm having trouble repainting it after the radio buttons are selected. I also don't even know if the radio buttons are doing anything... help is appreciated.
-Nate