Java Reference
In-Depth Information
Self-Test Exercises
5. Write code to create a button that has on it both the text
"Magic Button"
and the
picture in the file
wizard.gif
.
6. Write code to add the picture in the file
wizard.gif
to the
JPanel
named
picturePanel
. Assume that
picturePanel
has a
FlowLayout
manager.
7. Suppose you want to create a button that has the picture in the file
wizard.gif
on
it and no text. Suppose further that you want the button to have the action com-
mand
"Kazam"
. How would you create the button and set up the action command?
Scroll Bars
When you create a text area, you specify the number of lines that are visible and the
number of characters per line, as in the following example:
JTextArea memoDisplay =
new
JTextArea(15, 30);
The text area
memoDisplay
will have room for 15 lines of text, and each line will have room
for at least 30 characters. The user can enter more text, but only a limited amount of text
will be visible. It would be better not to have a firm limit on the number of lines or the
number of characters per line that the user can see in some convenient way. The way to
accomplish this is to add scroll bars to the text area, although, as you will see, the Java code
looks more like adding the text area to the scroll bars rather than the other way around.
When using scroll bars, the text is viewed through a
view port
that shows only part
of the text at a time. You can view a different part of the text by using the scroll bars
that are placed along the side and bottom of the view port. It is as if the text were writ-
ten on an unbounded sheet of paper, but the paper is covered by another piece of
paper with a rectangular cutout that lets you see only a portion of the text. The cutout
is the view port. This is illustrated in Display 18.6. You use the scroll bars to move the
view port so that different portions of the text can be seen through the cutout view
port. (You may prefer to think of the view port as fixed and the text as moving. These
two ways of thinking are equivalent.) Swing allows you to add scroll bars to your text
areas by using the class
JScrollPane
.
An object of the class
JScrollPane
is essentially a view port with scroll bars. When
you create a
JScrollPane
, you give the text area as an argument to the
JScrollPane
constructor. For example, if
memoDisplay
is an object of the class
JTextArea
(as created
in the line of code at the start of this subsection), you can place
memoDisplay
in a
JScrollPane
as follows:
view port
JScrollPane
JScrollPane scrolledText =
new
JScrollPane(memoDisplay);