import java.awt.*;
import java.awt.event.*;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.*;

// This is the same Bouncing Ball program, but as an application.
// Our class will extend JFrame instead of JApplet.
public class ControllerApp extends JFrame {
    JPanel buttonPanel = new JPanel();
    JButton runButton = new JButton("Run");
    JButton stopButton = new JButton("Stop");
    Timer timer;
        
    Model model = new Model();
    View view = new View(model);
    
//    @Override
//  For JApplets we need to override the inherited init() method.
//  An application still needs to create the GUI, but doesn't
//  inherit init(), so our init() method isn't overriding anything.
    public void init() {
      layOutComponents();
      attachListenersToComponents();
      // Connect model and view
      model.addObserver(view);
   }

    private void attachListenersToComponents() {
        runButton.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent event) {
                 runButton.setEnabled(false);
                 stopButton.setEnabled(true);
                timer = new Timer(true);
                timer.schedule(new Strobe(), 0, 40);
             }
          });
          stopButton.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent event) {
                runButton.setEnabled(true);
                stopButton.setEnabled(false);
                timer.cancel();
             }
          });
    }

    private void layOutComponents() {
        setLayout(new BorderLayout());
          this.add(BorderLayout.SOUTH, buttonPanel);
              buttonPanel.add(runButton);
              buttonPanel.add(stopButton);
              stopButton.setEnabled(false);
          this.add(BorderLayout.CENTER, view);
    }
    
    private class Strobe extends TimerTask {
        @Override
        public void run() {
            model.setLimits(view.getWidth(), view.getHeight());
            model.makeOneStep();
        }
    }
    
    // For an application, we need a main method. Here it is.
    public static void main(String[] args) {
        ControllerApp controllerApp = new ControllerApp();
        controllerApp.init();
        controllerApp.setSize(300, 300);
        controllerApp.setVisible(true);
        controllerApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

