Java Reference
In-Depth Information
Summary
In this chapter you have learned how to create an application window, and how to use containers in the
creation of the GUI for a program. We discussed the following important points:
The package
javax.swing
provides classes for creating a graphical user interface (GUI).
❑
A component is an object that is used to form part of the GUI for a program. All components
have the class
Component
as a superclass.
❑
A container is a component that can contain other components. A container object is created
with a class that is a subclass of
Container
. The classes
JPanel
,
JApplet
,
JWindow
,
JFrame
, and
JDialog
are containers.
❑
The class
JApplet
is the base class for an applet. The
JFrame
class is a base class for an
application window with a title bar, borders, and a menu.
❑
The arrangement of components in a container is controlled by a layout manager.
❑
The default layout manager for the content pane of
JFrame
,
JApplet
, and
JDialog
objects
is
BorderLayout.
❑
The
GridBagLayout
provides the most flexible control of the positioning of components in
a container. The position of a component in a
GridBagLayout
is controlled by a
GridBagConstraints
object.
❑
A
Box
container can be used to arrange components or containers in rows and columns. You
can use multiple nested
Box
containers in combination to create more complex arrangements
quite easily, that otherwise might require
GridBagLayout
to be used.
❑
A layout manager of type
SpringLayout
arranges components by applying constraints in
the form of
Spring
objects to their edges.
❑
A menu bar is represented by a
JMenuBar
object. Menu items can be objects of type
JMenu
,
JMenuItem
,
JCheckBoxMenuItem
, or
JRadioButtonMenuItem.
❑
You associate a pull-down menu with an item of type
JMenu.
❑
You can create a shortcut for a menu by calling its
setMnemonic()
method, and you can create
an accelerator key combination for a menu item by calling its
setAccelerator()
method.
❑
In the next chapter we will move on to look at events - that is, how we associate program actions with menu
items and components within a window, and how to close a window when the close icon is clicked.
Exercises
1.
Create an application, with a square window in the center of the screen that is half the height
of the screen by deriving your own window class from
JFrame
.
2.
Add six buttons to the application in the previous example in a vertical column on the left
side of the application window.