OOP2

ClockDigitalView.java

1
package be.uhasselt.oo2.mvc.app.clock;
2
3
import be.uhasselt.oo2.mvc.AbstractView;
4
import be.uhasselt.oo2.mvc.Controller;
5
import java.awt.Color;
6
import java.util.Observable;
7
import javax.swing.JComponent;
8
import javax.swing.JTextField;
9
10
/**
11
 * A digital clock View for the ClockModel. This View has no user inputs, so no 
12
 * Controller is required.
13
 * @author jvermeulen
14
 */
15
public class ClockDigitalView extends AbstractView {
16
    
17
    // The user interface for this view.
18
    private JTextField mClock;
19
    
20
    public ClockDigitalView(Observable model, Controller controller) {
21
        super(model, controller);
22
        init();
23
    }
24
    
25
    /**
26
     * Initializes the user interface.
27
     */
28
    private void init() {
29
        mClock = new JTextField();
30
    }
31
        
32
    /**
33
     * Updates the state of the on-screen digital clock.
34
     * Invoked automatically by ClockModel.
35
     * @param o The ClockModel object that is broadcasting an update
36
     * @param info A ClockUpdate instance describing the changes that have 
37
     * occurred in the ClockModel
38
     */
39
    @Override
40
    public void update(Observable o, Object info) {    
41
        // Cast info to ClockUpdate type.
42
        ClockUpdate clockInfo = (ClockUpdate) info;
43
        
44
        // Create a String representing the time.        
45
        String timeString = formatTime(clockInfo);
46
47
        // Display the new time in the clock text field.
48
        mClock.setText(timeString);
49
50
        // Fade the color of the display if the clock isn't running.
51
        if (clockInfo.isRunning()) {
52
          mClock.setBackground(Color.white);
53
        } else {
54
          mClock.setBackground(Color.gray);
55
        }
56
    }
57
    
58
    /**
59
     * Convenience method to return the user interface component. We don't need 
60
     * this if we implement View directly and directly subclass a GUI component.
61
     * @return the JComponent representing this View.
62
     */
63
    public JComponent getUI() {
64
        return mClock;
65
    }
66
    
67
    private String formatTime(ClockUpdate info) {
68
        return String.format("%d:%d:%d", 
69
                             info.getHour(), 
70
                             info.getMinute(), 
71
                             info.getSecond());
72
    }        
73
    
74
}
75