Java Digital Clock Program

Here's the rest of the code that makes up the digital clock. The program is made up of three classes:

  • TheTimestamp class that can give you the current hours, minutes, and seconds.

  • A class called “ClockView”. This holds everything related to the visual appearance of the clock on screen.

  • A class called “clock” that has overall control, and is where execution starts.

For a small example like this, we could merge everything into one class, and make it a dozen lines shorter. By keeping the design elements in separate classes, you can form a better idea of how classes should be used in bigger programs and systems.

The main() routine where execution starts

We'll start with the class that has overall control, where execution starts. Every Java application ever written starts in a method called “main” that has this general appearance.

image

As the diagram indicates, the name and parameters of a method are together known as the signature. The signature of a method comes up later in some other class features. Those three qualifiers at the front of the main name “public static void” always appear on the front of the main routine, so just take them as given for now. We've already seen that “void” means “this method does not have a return value”. Chapter 6 has an explanation of static if you want to peek ahead.

You write your main method, and put it in whichever of your classes is going to have overall control of the program.

The actual statements in our digital clock main routine are quite brief. Here they are in full (line numbers added on the left for ease of description):

1   public static void main(String[] args) {
2
3        ClockView cv = new ClockView();
4        cv.setVisible(true);
5         // loop about every 0.5 seconds
6        try {
7            for (;;) {
8               cv.refreshTimeDisplay();
9               Thread.sleep(500);
10           }
11       } catch (Exception e) {System.out.println("Error:"+e) ; }
12  }

Line 3 is the declaration of a variable to hold an instance of ClockView. That's the class that does everything to do with visual appearance, and it is coming up soon. Line 3 also initializes cv with a call to a constructor of ClockView. Now we have an object we can invoke methods on.

Line 4 calls the method setVisible() with an argument of true. We know that ClockView holds everything about the GUI, so it's a safe bet this makes it appear on the screen.

Line 5 is a comment.

Lines 6 and 11 are the start and end of a statement that says “try the code inside me, and if an error occurs take the action on line 11, i.e. print out a message.”

Lines 7 and 10 are the start and end of an infinite loop. Whatever is in the scope of the for loop will be repeated over and over until some external act stops it.

Line 8 calls the method refreshTimeDisplay() on object cv. That obviously puts the latest current time onto the screen.

Line 9 causes the program to sleep for 500 milliseconds (half a second). Thread is a class within the Java library. That's all there is to the main routine: call a ClockView routine to update the time on the screen, wait half a second, and do it again. Repeat forever.

The clock class

Putting the whole thing in a class, we end up with this code.

public class clock {

    public static void main(String args[]) {
        ClockView cv = new ClockView();
        cv.setVisible(true);
        // loop about every 0.5 seconds
        try {
            for (;;) {
              cv.refreshTimeDisplay();
              Thread.sleep(500);
            }
        } catch (Exception e) {System.out.println("Error:"+e) ; }
    }
}

Put the clock into a file called clock.java. You don't have any choice over the file name. A public class has to go into a file of the same name as the class, so it should be called clock.java. If you try to compile clock.java at this point, the compiler will complain that it cannot find any class called ClockView. We have used ClockView but not written it yet. The compiler needs to see the bytecode for all the classes that you use when you compile a file. This is needed so the compiler can check that you are using all the other methods and fields correctly. Let's go on to look at ClockView so we have a complete example.

The ClockView class

The last piece of the program is the class called ClockView. It contains everything related to the visual appearance of the clock on the screen. If you got tired of a digital clock, and wanted an analog clock with a face and hands, you would be able to achieve that by modifying this class only. The Timestamp and clock classes would not need to be changed at all. If you have ever done any maintenance programming, you'll understand what a benefit it is to separate the concerns. You get this benefit partly from Object Oriented Programming, and partly from a well thought-out design.

We'll base our clock display on two existing GUI components from the Java library. We'll use a JFrame as the small window to display the clock, and a JLabel to hold the digits of the time display. Both these classes are in package javax.swing. JFrame is a resizeable window with a menu bar, close icon etc. It's a convenient backdrop. JLabel is a fast cheap way to put read-only text on a GUI. It's ideal for displaying the time digits.

If you type the ClockView code in, you can put it in the same file as either Timestamp or clock, or put it in a file of its own. Sometimes it is convenient to put related classes in the same file. No two public classes can be in the same file, though. Here is the class, and it is followed by some notes at the end of the listing.

class ClockView extends javax.swing.JFrame {

    private javax.swing.JLabel tLabel = new javax.swing.JLabel();

    ClockView() {   // constructor
        this.setDefaultCloseOperation(
              javax.swing.WindowConstants.EXIT_ON_CLOSE);
        this.setSize(95,45);
        this.getContentPane().add(tLabel);
        this.refreshTimeDisplay();
    }

    protected String getDigitsAsString(int i) {
        String str = Integer.toString(i);
        if (i<10) str = "0"+str;
        return str;
    }

    public void refreshTimeDisplay() {
        Timestamp t = new Timestamp();
        t.fillTimes();
        String display = getDigitsAsString(t.hrs) + ":"
                     + getDigitsAsString(t.mins)  + ":"
                     + getDigitsAsString(t.secs);
        tLabel.setText("  " + display );
        tLabel.repaint();
    }
}

The first line of the class “... extends javax.swing.JFrame” is very important. It says that this class is based on some other class we have. This is an OOP concept called inheritance and it is important enough to have Chapter 8 devoted to it. Inheritance is what you get from your parents, and it means that ClockView has all the fields and methods of its parent, the JFrame class. That explains how the clock.main() routine can call a ClockView method called setVisible, even though we don't see setVisible() defined previously. It comes from the parent JFrame.

ClockView has one field, tLabel, and three methods. The first “method” is actually a constructor. When this is invoked, the run-time system allocates the storage for a ClockView object, then executes the statements in the body to initialize the new object. The initialization done in the constructor is a one-timeGUI set-up: the label is added to the frame, the frame is told that the program should exit if someone closes it, and the frame is given a size of 95 pixels wide by 45 pixels high.

The second method getDigitsAsString() takes the integer argument, and returns the equivalent string, zero-padded to be exactly two digits long. The plus sign in this method and the next one is not arithmetic addition. It is a special operator that is defined to take a string as the first operand and anything else as the second operand. It will convert the second operand into a string and append it onto the first string. In compiler terminology, you could say the “+” operator is overloaded for Strings.

The final method in ClockView is refreshTimeDisplay(). It creates a new Timestamp object and calls its fillTimes() method to get the most up-to-date time. Then it assembles those values into a string containing hours, minutes and second separated by colons. Finally, it updates the label with this string, and calls repaint() to make the new text appear on the screen. Again, repaint is a library call that tells the GUI “some part of this component may have changed, please update that part of the screen with the new appearance”.

In describing these classes there are several places where we've used a library class. When you start out as a Java programmer, that large API is an unknown for you. But the library classes are as important as learning the language; you need to learn them both. As we go through the book, most chapters will present a class or two from the API, starting with the ones you'll use most. We'll also suggest some tips on how to learn more of the API. A lot of people have already trodden that path, and it has a gentle gradient.

Compiling and running the Digital Clock program

At last you can compile the code and run the complete clock program. You'll run the javac compiler and give the names of the source code files you created. If you put all three classes in one file, the command will be:

javac clock.java

If you put each class in its own file, the command will be something like:

javac clock.java  Timestamp.java  ClockView.java

(use the actual filenames you used, and note that class names are case-sensitive, and file names should match exactly). You're sure to make a couple of typing mistakes the first couple of times, and the compiler will give you error messages with the line numbers. Correct all those, and repeat until you get a clean compilation. The compiler will create three new files, one for each class it found. The files will be clock.class, Timestamp.class and ClockView.class. These files will contain byte code.

When you get a clean compilation of all three classes, you can run the program by typing:

java clock

That will cause the JVM to look for the file clock.class, load it, and run its main() method. Here's the result on Windows, shown in Figure 2-4.

Figure 2-4. Compiling and running the clock program

image
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.18.141