Java Reference
In-Depth Information
GUI pieces—the status line, the table list of accounts, and the buttons. The
JFrame is a bit odd here, in that you have to add objects to its content pane;
other container objects you can just add to directly. (We could have done the
getContentPane() once, store the result in an intermediate variable, and do
the adds to it, but the efficiency gain is unimportant here because we only need
to do this once, to get the GUI started.)
When we've got it built, we pack the frame, and make it visible:
frame.pack();
frame.setVisible(true);
That's the basic core of what you need to do with any GUI: construct its
pieces, add them to the frame, pack the frame, and make it visible. Now you're
off and running. The rest is just details.
16.7.2
The three pieces that we create—the status, the list, and the buttons—will each
package up their objects into an intermediate container, a JPanel , and return
that container to main() . This not only serves to chunk the problem into
fewer pieces (just three parts, not eight or more), but also helps with the
formatting. Each piece can format its objects relative to each other. Then
main() only has to lay out the three big pieces. So watch for each of the
create...() methods to return a JPanel —a good approach when you build
your GUIs, too.
The JPanel s returned to main() are just Swing objects. They, like the
buttons or labels (that we will see here shortly), just get added into other con-
tainers. For main() , that container is the JFrame , the main window. Any
container will have a layout manager, the mechanism by which objects are
placed in that container. For JFrame , the default is the BorderLayout manag-
er. When you call the add() method on a container using a BorderLayout ,
you can specify (as a second parameter to the add() method) where the
object being added will get placed. The constants defined for placing
objects are NORTH , SOUTH , EAST , WEST , or CENTER —hence the “Border” of
BorderLayout . There are also relative position values: PAGE_START ,
PAGE_END , LINE_START , and LINE_END which are just like north, south, west,
and east, respectively, provided that the ComponentOrientation is set to
LEFT_TO_RIGHT . (If you really want to know, check the Javadoc page for
java.awt.BorderLayout .)
Creating Pieces
Search WWH ::




Custom Search