import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

class TrafficLight {
  String state;
  public TrafficLight(String state) {
    this.state = state;
  }
  public void next() {
    if(this.state.equals("green")) { this.state = "yellow"; }
    else if(this.state.equals("yellow")) { this.state = "red"; }
    else { this.state = "green"; }
  }
}

class TrafficLightDrawing extends JPanel {
  TrafficLight tl;
  public TrafficLightDrawing(TrafficLight tl) {
    this.tl = tl;
    this.setFocusable(true);
  }

  public void paintComponent(Graphics g) {

    g.fillRect(290, 10, 120, 310);

    Color topColor = Color.GRAY;
    Color middleColor = Color.GRAY;
    Color bottomColor = Color.GRAY;

    if(tl.state.equals("green")) { bottomColor = Color.GREEN; }
    else if(tl.state.equals("yellow")) { middleColor = Color.YELLOW; }
    else if(tl.state.equals("red")) { topColor = Color.RED; }

    g.setColor(topColor);
    g.fillOval(300, 20,    80,   80);

    g.setColor(middleColor);
    g.fillOval(300, 120,    80,   80);

    g.setColor(bottomColor);
    g.fillOval(300, 220,    80,   80);

  }

}

class ChangeLightKey implements KeyListener {
  TrafficLight tl;
  JFrame frame;
  public ChangeLightKey(TrafficLight tl, JFrame frame) {
    this.tl = tl;
    this.frame = frame;
  }
  public void keyPressed(KeyEvent e) { }
  public void keyReleased(KeyEvent e) { }
  public void keyTyped(KeyEvent e) {
    if(e.getKeyChar() == 'n') {
      this.tl.next();
      this.frame.repaint();
    }
    System.out.println("It was typed: " + e.getKeyChar()); 
  }
}

class ChangeLightAction implements ActionListener {
  TrafficLight tl;
  JFrame frame;
  public ChangeLightAction(TrafficLight tl, JFrame frame) {
    this.tl = tl;
    this.frame = frame;
  }
  public void actionPerformed(ActionEvent e) {
    this.tl.next();
    this.frame.repaint();
    System.out.println("It was clicked!");
  }
}

public class GUI {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    TrafficLight tl = new TrafficLight("red");
    TrafficLightDrawing tld = new TrafficLightDrawing(tl);

    JButton button = new JButton();
    button.setText("Advance Light");
    ChangeLightAction cla = new ChangeLightAction(tl, frame);
    button.addActionListener(cla);

    tld.addKeyListener(new ChangeLightKey(tl, frame));

    frame.setMinimumSize(new Dimension(800, 600));

    frame.add(button, BorderLayout.PAGE_START);
    frame.add(tld, BorderLayout.CENTER);

    frame.setVisible(true);

    System.out.println("Main has ended.");
  }
}
