Home
01 Getting Started
02 Concepts
03 Variables & Data Types
04 Control Logic
05 Modifiers
06 GUI
07 Other Useful Classes
08 Handling Events
09 Handling Exceptions
10 Project 01 - Mortg Calc
11 More on Applets
12 Layout Manager
13 Project 02 - Calculator
14 Threads
15 Project 03 - Wake Up
a Part A - Build the Look
b Part B - Display Time
c Part C - Add Alarm Beep
d Part D - Play Radio
16 File I/O
17 Project 04 - File I/O
Expanded Table of Contents
Debugging Hints
HTML Review
Download Samples
|
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
|
|