Learning Java
Custom Search

Previous Next

Part B - Wake Up - Display Time

In this step, we will add the display of the changing time. We will use a GregorianCalendar object to get the current time.

    GregorianCalendar xday = new GregorianCalendar();
    String xtime = xday.getTime().toString();
Before we had used a literal to represent where the time should be. So now, we want to replace this literal with our variable, xtime, that contains the changing time.
Replace
    screen.drawString("DDD MMM 31 99:99:99 EDT 2008", 5,15);
with
    screen.drawString(xtime, 5, 15);

The problem with this display is that as the time value changes, the modified value overlays what was there and it becomes unreadable.

What is needed is to erase the old time display before showing the new time display. Erase it by rewriting the old time with the current background color. Then the new time can be written on the cleared area using the desired foreground color.

    String lastTime = "";

    screen.setColor(getBackground());
    screen.drawString(lastTime, 5, 15);

    lastTime = xtime;

These changes all take place in the class DteTimePanel which now looks like the following. The rest of the code has not changed.

class DteTimePanel extends JPanel {
    String lastTime = "";

    public void paint(Graphics screen) {
        GregorianCalendar xday = new GregorianCalendar();
        String xtime = xday.getTime().toString();

	Color fgColor = new Color(40, 120, 160);
        Font type = new Font("Monospaced", Font.BOLD, 20);
        screen.setFont(type);
        screen.setColor(getBackground());
        screen.drawString(lastTime, 5, 15);
        screen.setColor(fgColor);
        screen.drawString(xtime, 5, 15);
        lastTime = xtime;
        repaint();
    }
}

Previous Next

Steps In Learning

Contact us

Copyright © 2008      N. Nelson      All Rights Reserved