Sunday, 10 May 2015

Understanding Java Program Flow


One of the biggest hurdles for non-object-oriented developers to clear is simply understanding exactly what is going on within an object-oriented application. At times, it appears that methods are being called by some invisible force within your computer. GUI environments such as Windows, Macintosh, and Motif just add to this apparent state of confusion because operating system events are constantly being funneled to the application responsible for trapping those events.

The Applet Life Cycle

Think about what is actually required to create a simple Visual Basic form. The form is first created, and any controls that need to be added to it are done at this time. By default, this form is automatically created and shown when the application is run. How does this happen? As you might expect, there is a lot more going on in the background than meets the eye.

The first thing you must understand is how applications run in multitasking operating environments. The Windows environment continually handles messages from a variety of hardware and software sources. It then in turn "forwards" these messages on to each application that is currently "listening." Your application actually has a single entry point that Windows first calls. The basic operations that go on inside this entry point look something like this (please pardon the extreme pseudo-code!):
Entry Point HEY_WINDOWS!(int MESSAGE) 
{
/* Process all of the messages your application needs */
if MESSAGE = FORM_CREATE then...
else if MESSAGE = FORM_SHOW then...
else if MESSAGE = FORM_DESTROY then...
...
}
As you can see, Visual Basic provides an easy-to-use GUI over the top of these low-level events. By clicking on a form's events screen, you will see a simple column of events that the Visual Basic designers chose for your form to handle. Experienced Visual Basic programmers know that you can actually process any Windows event you choose to handle, but this set of events is the most commonly used.

C++, Delphi, and Visual Basic programs all use this message-passing system in the exact same ways. What is interesting about all three of these is the way that the respective languages allow designers to hide implementation details from application developers. The Java language is an extension of this methodology. However, instead of the Windows operating system handling messages and passing them directly to a Visual Basic application, programmers in Java receive their GUI messages from something called the Advanced Windowing Toolkit (AWT). 

Listing 6.4. The JDK sample application MouseTrack.
1:  import java.awt.Graphics; 
2:  import java.lang.Math;
3:
4:  public class MouseTrack extends java.applet.Applet {
5:
6:      int mx, my;
7:      int onaroll;
8:
9:      public void init() {
10:         onaroll = 0;
11:         resize(500, 500);
12:     }
13:
14:     public void paint(Graphics g) {
15:g.drawRect(0, 0, size().width - 1, size().height - 1);
16: mx = (int)(Math.random()*1000) % (size().width -
     (size().width/10));
17: my = (int)(Math.random()*1000) % (size().height -
     (size().height/10));
18: g.drawRect(mx, my, (size().width/10) - 1, (size().height/10) - 1);
19:     }
20:
21:    /*
22:     * Mouse methods
23:     */
24: public boolean mouseDown(java.awt.Event evt,int x,        int y) {
25:         requestFocus(); 
26:         if((mx < x && x < mx+size().width/10-1) &&
     (my < y && y < my+size().height/10-1)) { 
27:             if(onaroll > 0) {
28:                 switch(onaroll%4) {
29:                 case 0:
30:play(getCodeBase(),"sounds/tiptoe.thru.the.tulips.au")    ;
31:                     break; 
32:                 case 1:
33:play(getCodeBase(), "sounds/danger,danger...!.au");
34:                     break; 
35:                 case 2:
36:play(getCodeBase(), "sounds/adapt-or-die.au");
37:                     break; 
38:                 case 3:
39:play(getCodeBase(), "sounds/cannot.be.completed.au");
40:                     break; 
41:                 }
42:                 onaroll++;
43:                 if(onaroll > 5)
44:getAppletContext().showStatus("You're on your way to
     THE HALL OF FAME:" + onaroll + "Hits!"); 
45:                else 
46:getAppletContext().showStatus("YOU'RE ON A ROLL:"
     + onaroll + "Hits!");
47:             }
48:             else {
49:getAppletContext().showStatus("HIT IT AGAIN!               AGAIN!"); 
50:play(getCodeBase(), "sounds/that.hurts.au");
51:                 onaroll = 1;
52:             }
53:         }
54:         else {
55:getAppletContext().showStatus
   "You hit nothing at (" + x + ", " + y + "), exactly");
56: play(getCodeBase(), "sounds/thin.bell.au");
57:             onaroll = 0;
58:         }
59:         repaint(); 
60:         return true;
61:     }
62:
63:public boolean mouseMove(java.awt.Event evt, int x,       int y) {
64:         if((x % 3 == 0) && (y % 3 == 0))
65:             repaint();
66:         return true;
67:     }
68:
69:     public void mouseEnter() {
70:         repaint(); 
71:     }
72:
73:     public void mouseExit() {
74:         onaroll = 0;
75:         repaint(); 
76:     }
77:
78:     /**
79:      * Focus methods
80:      */
81:     public void keyDown(int key) {
82:         requestFocus(); 
83:         onaroll = 0;
84:         play(getCodeBase(), "sounds/ip.au");
85:     }
86: }

As can be seen by examining the code listing for this applet, there is quite a bit of work going on here. Events are being trapped, multimedia work is being done, and objects are being painted on the screen. Examining each section of code should allow the reader to gain an appreciation for the power of the Java language.

In lines 1 and 2, MouseTrack imports the AWT's Graphics class and a Math class for calculation purposes. This operation is never done in Visual Basic because inheritance is not allowed. In other words, when an object is declared as type Form, the Visual Basic compiler automatically knows what code to go grab in order to compile. In an object-oriented system, MouseTrack could be the child of any number of classes. However, because it is an applet, it must inherit directly, or indirectly, from Applet.

In line 4, MouseTrack is declared to inherit from the java.applet.Applet class. By default, this identifies this class as the main class of this application.

In lines 6 and 7, member variables are declared. These variables are visible to everything inside the class. In addition, any other application that created a MouseTrack class within it could have access to these variables.

In line 9, the init() method is declared. By inheriting from the Applet class, each applet inherits four "life-cycle" functions: init()start()stop(), and destroy()Init() is called once after an applet is initially loaded.

In lines 10 and 11, the applet is initialized. Note the resize() member call. Don't be confused just because this method isn't declared within this class. The Resize method is inherited from the Applet class.

In line 14, there is another "magic" method call. Where is this coming from? Notice that nowhere in this entire class is the paint() method actually invoked. However, the repaint() method is called in several situations. The paint() method is called whenever the AWT thinks the window needs to be redrawn, or when a repaint() is requested.

Lines 15 through 18 are used to draw the square at random locations on the screen. Note the use of the Math.random() method here. This is why the java.lang.Math class was imported on line 2.

In line 24, the mouseDown method is called whenever the AWT detects a mouse click over this applet's screen area.

In line 25, the requestFocus() method is called. This method is equivalent to Visual Basic's SetFocus().

In lines 26 through 42, some checks are done to determine whether the user successfully clicked inside the square. What is especially interesting is the play() call in lines 30, 33, 36, and 39. At first glance, this call simply plays a sound file depending on the frequency of the user's hits. However, note the call getCodeBase(). This instructs the play function to retrieve the sound file from the applet's base location. In other words, if the applet was retrieved from a Web server in Tokyo, play the sound file located there. In one function call, you have reached across the world, retrieved a sound file, and played it on a user's computer…platform notwithstanding. This type of functionality would have been unimaginable a couple of years ago, but such is the pace of change.

In lines 43 through 61, depending on the user's hit count, several messages are displayed. The showStatus() method will print the message in the appletContext's status window. With most Web browsers, this message will be displayed in the lower-left corner status window (see Figure 6.2 where the text "Applet MouseTrack running" is displayed).

In line 63, mouseMove() is called whenever a MouseMove message is generated.

In lines 64 through 66, the mouseMove() method forces a repaint every three units (probably pixels). By examining the contents of the paint() method, you can see that this will redraw the square on the screen. 

In line 69, the mouseEnter() method is called whenever the mouse cursor enters the screen area of this applet. This function also forces a repaint.

In line 73, the mouseExit() method is called whenever the mouse leaves the screen area of the applet. This function will force a repaint and reset the user's score.

In lines 81 through 86, the keyDown() method is called whenever any key is hit. The applet will request focus and, once again, a sound will be played to notify the user.

This applet may be much simpler than a typical Visual Basic form, but it provides some useful illustrations. Hopefully, the Visual Basic developer will see that the overall development goal remains the same. GUI events still need to be handled, and many of the user interface elements remain the same. Object-oriented programming is a skill that Visual Basic developers will need to acquire, but Windows application development skills do provide valuable insight into the Java AWT. 

No comments:

Post a Comment