Java Reference
In-Depth Information
Thread.sleep
Thread.sleep
is a static method in the class
Thread
that pauses the thread that includes
the invocation. It pauses for the number of milliseconds (thousandths of a second) given as
an argument.
The method
Thread.sleep
may throw an
InterruptedException
, which is a checked
exception and so must be either caught in a
catch
block or declared in a
throws
clause.
The classes
Thread
and
InterruptedException
are both in the package
java.lang
,
so neither requires any import statement.
Note that
Thread.sleep
can be invoked in an ordinary (single thread) program of the kind
we have seen before this chapter. It will insert a pause in the single thread of that program.
SYNTAX
Thread.sleep(
Number_Of_Milliseconds
);
EXAMPLE
try
{
Thread.sleep(100); //Pause of 1/10 of a second
}
catch
(InterruptedException e)
{
System.out.println("Unexpected interrupt");
}
The
getGraphics
Method
The other new method in Display 19.1 is the
getGraphics
method, which is used in
the following line from the method
fill
:
getGraphics
Graphics g = box.getGraphics();
The
getGraphics
method is almost self-explanatory. As we already noted
in Chapter 18, almost every item displayed on the screen (more precisely, every
JComponent
) has an associated
Graphics
object. The method
getGraphics
is an accessor method that returns the associated
Graphics
object (of the calling
object for
getGraphics
)—in this case, the
Graphics
object associated with the panel
box. This gives us a
Graphics
object that can draw circles (or anything else) in the
panel box.
We still need to say a bit more about why the program in Display 19.1 makes you
wait before it will respond to the close-window button, but otherwise this concludes
our explanation of Display 19.1. The rest of the code consists of standard things we
have seen before.