Programming Resources
For Fun and Learning
Charles Cusack
Computer Science
Hope College
main

Python
C++
JAVA
PHP
SQL

Assignments


Clock-Broken


ClockPanel.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

/**
 * A Clock GUI. 
 * 
 * Displays a clock.
 * 
 * Draws the time in red.
 * Displays the alarm going off by painting the time in green.
 * 
 * @author Charles Cusack
 * @version August 2008
 */

public class ClockPanel extends JPanel implements ClockListener
{
    public static final int width = 100;
    public static final int height = 70;

    private Clock myClock;
    private boolean alarmRinging;
    
    /**
     * Constructor for objects of class Clock
     */
    public ClockPanel()
    {
        myClock = new Clock();
        alarmRinging = false;
        
        // Set the alarm for 10 seconds from now.
        // Makes it easy to test that alarm is working.
        Time alarm = new Time();
        alarm.setTime(myClock.getTime());
        alarm.addSeconds(10);
        myClock.setAlarmTime(alarm);
        myClock.setAlarm();
        
        myClock.addClockListener(this);
    }
    
    // Overriding the paintComponent from JPanel
    public void paintComponent(Graphics g) {
        super.paintComponent(g);    
        if(alarmRinging) 
        {
            g.setColor(Color.green);
        } 
        else 
        {
            g.setColor(Color.red);
        }
        g.setFont(new Font("Times Roman",Font.BOLD,18));
        g.drawString(myClock.getTime().toString(),10,16);
    }  
    
    /**
     * Run a program that displays the clock in a JFrame
     * 
     * @param args command line arguments that are not used.
     */
    public static void main(String[] args) {  

        ClockPanel clockPanel = new ClockPanel();
        JLabel titleLabel = new JLabel("Current Time:");
        
        JFrame theFrame = new JFrame();
        theFrame.setTitle("A Clock");
        Container cont=theFrame.getContentPane();
        cont.add(titleLabel,BorderLayout.NORTH);
        cont.add(clockPanel,BorderLayout.CENTER);
  
        theFrame.pack(); 
        theFrame.setSize(new Dimension(width,height));
        theFrame.setVisible(true);         
        
        // Add window listener so it closes properly.
        theFrame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
        }});  
    }

    //-----------------------------------------------------------------
    // The following three methods are from the ClockListener interface
    
    public void timeChanged(ClockEvent e) 
    {
        repaint();
    }
    public void alarm(ClockEvent e)
    {
        alarmRinging = true;
        repaint();
    }
    public void alarmEnded(ClockEvent e)
    {
        alarmRinging = false;
        repaint();
    }
}