Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

180 HOUR 13:Building a Simple User Interface


You can specify a string in the JTextArea()constructorto be displayed in
the text area, using the newline character(\n) to send text to the next line,
as in the following:
JTextArea comments = new JTextArea(“I should have been a pair\n”
+ “of ragged claws.”, 10, 25);

Panels
The last components you learn to create during this hour are panels, which
are created in Swing using the JPanelclass. JPanelobjectsare the simplest
kind of container you can use in a Swing interface. The purpose of JPanel
objects is to subdivide a display area into different groups of components.
When the display is divided into sections, you can use different rules for
how each section is organized.
You can create a JPanelobject and add it to a container with the following
statements:
JPanel topRow = new JPanel();
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(topRow);

Panels are often used when arranging the components in an interface, as
you see in Hour 14, “Laying Out a User Interface.”
You add components to a panel by calling its add()method. You can
assign a layout manager directly to the panel by calling its setLayout()
method.
You can also use panels when you need an area in an interface to draw
something, such as an image from a graphics file.
Another convenient use of JPanelis to create your own components that
can be added to other classes. This is demonstrated in this hour’s work-
shop.

Creating Your Own Component
An advantage of OOPis the capability to reuse classes in different projects.
For the next project, you create a special panel component that you can
reuse in other Java programs. The component, ClockPanel, displays the
current date and time in a manner similar to the ClockTalkproject from
Hour 7, “Using Conditional Tests to Make Decisions.”

CAUTION
Te x t a r e a c o m p o n e n t s b e h av e
in ways you might not expect—
they expand in size when the
user reaches the bottom of the
area,and do not include scroll-
bars along the right edge or
bottom edge. To implement the
kind of text areas you see in
other GUI software,you must
place the area inside a contain-
er called a scroll pane,as you
see in Hour 16,“Building a
Complex User Interface.”

Free download pdf