Java Reference
In-Depth Information
getGraphics
Every
JComponent
has an associated
Graphics
object. The method
getGraphics
is an
accessor method that returns the associated
Graphics
object of its calling object.
SYNTAX
Component
.getGraphics( );
EXAMPLE (see Display 19.1 for context)
Graphics g = box.getGraphics( );
Fixing a Nonresponsive Program Using Threads
Now that we have discussed the new items in the program in Display 19.1, we are
ready to explain why it is nonresponsive and to show you how to use threads to write a
responsive version of that program.
Recall that when you run the program in Display 19.1, it draws circles one after
the other to fill a portion of the frame. Although there is only a 1/10 of a second pause
between drawing each circle, it can still seem like it takes a long time to finish. So, you
are likely to want to abort the program and close the window early. But, if you click
the close-window button, the window will not close until the GUI is finished drawing
all the circles.
Here is why the close-window button is nonresponsive: The method
fill
, which
draws the circles, is invoked in the body of the method
actionPerformed
. So, the
method
actionPerformed
does not end until after the method
fill
ends. And, until
the method
actionPerformed
ends, the GUI cannot go on to do the next thing,
which is probably to respond to the close-window button.
Here is how we fixed the problem: We have the method
actionPerformed
create
a new (independent) thread to draw the circles. Once
actionPerformed
does this,
the new thread is an independent process that proceeds on its own. The method
actionPerformed
has nothing more to do with this new thread; the work of
actionPerformed
is ended. So, the main thread (the one with
actionPerformed
) is
ready to move on to the next thing, which will probably be to respond promptly to a
click of the close-window button. At the same time, the new thread draws the circles.
So, the circles are drawn, but at the same time a click of the close-window button will
end the program. The program that implements this multithreaded solution is given in
the next Programming Example.
EXAMPLE:
A Multithreaded Program
Display 19.2 contains a program that uses a main thread and a second thread to
implement the technique discussed in the previous subsection. The general approach
was outlined in the previous subsection, but we need to explain the Java code details.
We do that in the next few subsections.