OOP2

ClockDigitalView.java

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