OOP2

Clock.java

1
import java.awt.event.WindowAdapter;
2
import java.awt.event.WindowEvent;
3
import javax.swing.BoxLayout;
4
import javax.swing.JFrame;
5
6
/**
7
 * Main user interface for the application. Makes sure the model, views and
8
 * controllers are connected to each other.
9
 * @author jvermeulen
10
 */
11
public class Clock {
12
    // The clock data (i.e., the Model).
13
    private ClockModel mModel;
14
    
15
    // A digital view of the clock.
16
    private ClockDigitalView mDigitalView;
17
    
18
    // A toolbar for controlling the clock.
19
    private ClockTools mTools;
20
    
21
    // An analog view of the clock.
22
    private final ClockAnalogView mAnalogView;
23
    
24
    public Clock(int hour, int minute, int second) {
25
        // Create the data model.
26
        mModel = new ClockModel();
27
28
        // Create the digital clock view.
29
        mDigitalView = new ClockDigitalView(mModel, null);
30
        mModel.addObserver(mDigitalView);
31
32
        // Create the analog clock view.
33
        mAnalogView = new ClockAnalogView(mModel, null);
34
        mModel.addObserver(mAnalogView);
35
        
36
        // Create the clock tools view.
37
        mTools = new ClockTools(mModel, null);
38
        mModel.addObserver(mTools);
39
        
40
        // Set the time.
41
        mModel.setTime(hour, minute, second);
42
43
        // Start the clock ticking.
44
        mModel.start();
45
    }
46
    
47
    public void createGUI() {
48
        JFrame frame = new JFrame("Clock");
49
        frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
50
        frame.getContentPane().add(mDigitalView.getUI());
51
        frame.getContentPane().add(mAnalogView);
52
        frame.getContentPane().add(mTools.getUI());                
53
        frame.addWindowListener(new WindowAdapter() {
54
            @Override
55
            public void windowClosing(WindowEvent e) {
56
                System.exit(0);
57
            }
58
        });
59
        frame.pack();
60
        frame.setVisible(true);
61
    }
62
    
63
    private static void createAndShowGUI() {
64
        Clock clock = new Clock(9, 10, 22);
65
        clock.createGUI();
66
    }
67
    
68
    public static void main(String[] args) {
69
        //Schedule a job for the event-dispatching thread:
70
        //creating and showing this application's GUI.
71
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
72
            @Override
73
            public void run() {
74
                createAndShowGUI();
75
            }
76
        });
77
    }
78
}
79