Java Reference
In-Depth Information
throughout pre-5.0 code. Today, the use of
getContentPane( )
is no longer necessary. You
can simply call
add( )
,
remove( )
, and
setLayout( )
directly on
JFrame
because these
methods have been changed so that they automatically operate on the content pane.
The
setVisible( )
method has this general form:
void setVisible(boolean
flag
)
If
flag
is
true
, the window will be displayed. Otherwise, it will be hidden. By default, a
JFrame
is invisible, so
setVisible(true)
must be called to show it.
Inside
main( )
, a
SwingDemo
object is created, which causes the window and the label
to be displayed. Notice that the
SwingDemo
constructor is invoked using these lines of
code:
This sequence causes a
SwingDemo
object to be created on the
event-dispatching thread
rather than on the main thread of the application. Here's why. In general, Swing programs
are event-driven. For example, when a user interacts with a component, an event is gen-
erated. An event is passed to the application by calling an event handler defined by the
application. However, the handler is executed on the event-dispatching thread provided by
Swing and not on the main thread of the application. Thus, although event handlers are
defined by your program, they are called on a thread that was not created by your program.
To avoid problems (such as two different threads trying to update the same component at
the same time), all Swing GUI components must be created and updated from the event-
dispatching thread, not the main thread of the application. However,
main( )
is executed on
the main thread. Thus, it cannot directly instantiate a
SwingDemo
object. Instead, it must
create a
Runnable
object that executes on the event-dispatching thread, and have this ob-
ject create the GUI.
To enable the GUI code to be created on the event-dispatching thread, you must use
one of two methods that are defined by the
SwingUtilities
class. These methods are
in-
vokeLater( )
and
invokeAndWait( )
. They are shown here: