Event-Driven Programs


GUI-based programs are fundamentally different from the applications you saw and wrote prior to Chapter 14 ("Painting"). The earlier programs began execution at the beginning of the main() method, ran through the end of main(), and that was that. When main() was finished, the program was finished. The Java Virtual Machine ceased to exist, and you saw a new prompt in your console window.

Now consider the behavior of an application with a GUI. The following code creates a frame that contains a button and displays a blue circle:

import java.awt.*; public class Xxxx extends Frame {   Xxxx()   {     setLayout(new FlowLayout());     Button btn = new Button("Push Me");     add(btn);     setSize(300, 300);   }   public void paint(Graphics g)   {     g.setColor(Color.blue);     g.fillOval(100, 100, 100, 100);   }   public static void main(String[] args)   {     (new Xxxx()).setVisible(true);   } }

Figure 16.1 shows the GUI.


Figure 16.1: A GUI waiting for events

There is something mysterious about this code's behavior, and indeed about the behavior of all the GUI-based applications you saw in Chapters 14 and 15. In fact, there are two mysteries, and perhaps you have already wondered about them.

  • The main() method consists of a single line. After the instance of class Xxxx has been constructed and made visible, one would expect the program to terminate. This is not the case. The JVM continues to run (but doing what?) until someone types Ctrl+C into the console window. It is only then that the frame vanishes and the console is ready to accept a new command.

  • The application does not call paint() anywhere. The method is implemented but never invoked. But something somewhere must have called it, because the circle is right there in the middle of the frame. Who called paint()?

Something within the Java Virtual Machine seems to be keeping an eye on things on our behalf, calling paint() at the right time and keeping the GUI alive after main() finishes. You could almost say the JVM has multiple personalities: One personality to run main(), and one to take care of the mysterious GUI behavior.

In fact, the JVM has the computer equivalent of multiple-personality disorder. Don't worry! For computers it's a good thing, because the personalities function together harmoniously. We say that the JVM is multithreaded, which means it is capable of performing more than one task at a time. Each task is called a thread. Java's threading capabilities are powerful and intricate. You can write applications that create several or many threads, each performing its own task. Creating your own threads and maintaining harmony among them is far beyond the scope of this book. In order to understand GUI event processing, you don't need to know any details about creating or managing threads. But you do need to know a little bit about what threads are. As you'll see in the next section, my own exposure to threads began many years ago in a barbershop.

Threads

I was eight years old. I was waiting my turn to get my hair cut, and I was reading a Superman comic book. The Man of Steel was entertaining some kids at an orphanage by playing ping-pong against himself. He would serve the ball, and then run at super-speed to the other side of the table to return the ball. Then he would run back to the original side, and so on. Each time he changed sides, he ran so fast that nobody could see him, and he ended up exactly where he had been before. This created the illusion of two identical Supermen.

Computers do something similar. They create the illusion of doing several things simultaneously by rapidly switching from one task to another, many times each second, like Superman running from one side of the ping-pong table to the other. The individual tasks are called threads.

Thread support is built into the Java language and the JVM. When you run an application, even a very simple one that just prints out a message from main(), there are actually two threads the work. One of these is called the main thread. Its job is to execute your main() method. Until you began working with GUIs, all behavior of all the applications you wrote came from the main thread.

The second thread is called the garbage collection thread. Recall from Chapter 6, "Arrays," that Java's garbage-collection feature recycles memory from objects and arrays when they can be used no longer. This recycling happens while your program is executing. In other words, the main thread and the garbage collection thread operate simultaneously. You don't have to do anything special to make the garbage collection thread work; it is created automatically by the JVM.

Another thread that is created automatically as part of the JVM infrastructure is the event dispatch thread, also known as the GUI thread. It is not present in all applications; it appears only in applications with GUIs. The Event dispatch thread knows when the display needs to be redrawn and calls paint() at the appropriate moment. As you will see later in this chapter, it is the Event dispatch thread that knows when components have been activated and calls the appropriate methods in the appropriate objects.

The presence of an Event dispatch thread affects the life cycle of the JVM. If an application has no GUI, the JVM terminates when the main thread finishes its work. However, if an Event dispatch thread is present, the JVM continues to run after the main thread is done. The JVM remains in existence until the Event dispatch thread terminates. Typically, this happens when the Event dispatch thread executes a System.exit() call.

It is easy to imagine what the JVM is doing while the main thread is alive. Mostly, the JVM is executing the application's bytecode, but now and then the garbage collection thread recycles some memory. But what about a GUI application, where main() calls the constructor of a Frame subclass, calls setVisible() on the constructed object, and then is done? At this point the frame is on the screen, just sitting there. You saw this in numerous examples in the previous chapter. If the frame is doing nothing, and main() has terminated, what is the JVM doing?

The answer is: Absolutely nothing! The Event dispatch thread is lurking in the background, waiting for the user to do something that requires attention. For example, if the frame becomes covered by another frame and is subsequently uncovered, the Event dispatch thread will call paint() so that the screen can be updated. It is also the job of the Event dispatch thread to notice when user input has occurred, and to respond appropriately by making certain method calls to certain objects.

We say that Java GUI programs are event-driven. This means that after some initialization, the programs only act in response to user input. An event is a single unit of user input. In the next section, you will learn about Java's simplest type of event.




Ground-Up Java
Ground-Up Java
ISBN: 0782141900
EAN: 2147483647
Year: 2005
Pages: 157
Authors: Philip Heller

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net