Java Reference
In-Depth Information
17
// Set the font in the label and the text field
18 jlblImageTitle.setFont(
new
Font(
"SansSerif"
, Font.BOLD,
16
));
19 jtaDescription.setFont(
new
Font(
"Serif"
, Font.PLAIN,
14
));
20
21
// Set lineWrap and wrapStyleWord true for the text area
jtaDescription.setLineWrap(
true
);
wrap line
wrap word
read only
22
23
24
25
26
// Create a scroll pane to hold the text area
27 JScrollPane scrollPane =
new
JScrollPane(jtaDescription);
28
29
// Set BorderLayout for the panel, add label and scroll pane
30 setLayout(
new
BorderLayout(
5
,
5
));
31 add(scrollPane, BorderLayout.CENTER);
32 add(jlblImageTitle, BorderLayout.WEST);
33 }
34
35
/** Set the title */
36
public void
setTitle(String title) {
37 jlblImageTitle.setText(title);
38 }
39
40
/** Set the image icon */
41
public void
setImageIcon(ImageIcon icon) {
42 jlblImageTitle.setIcon(icon);
43 }
44
45
/** Set the text description */
46
public void
setDescription(String text) {
47 jtaDescription.setText(text);
48 }
49 }
jtaDescription.setWrapStyleWord(
true
);
jtaDescription.setEditable(
false
);
scroll pane
The text area is inside a
JScrollPane
(line 27), which provides scrolling functions for
the text area. Scroll bars automatically appear if there is more text than the physical size of the
text area.
The
lineWrap
property is set to
true
(line 22) so that the line is automatically wrapped
when the text cannot fit in one line. The
wrapStyleWord
property is set to
true
(line 23) so
that the line is wrapped on words rather than characters. The text area is set as noneditable
(line 24), so you cannot edit the description in the text area.
It is not necessary to create a separate class for
DescriptionPanel
in this example.
However, this class was created for reuse in the next section, where you will use it to display
a description panel for various images.
L
ISTING
17.3
TextAreaDemo.java
1
import
java.awt.*;
2
import
javax.swing.*;
3
4
public class
TextAreaDemo
extends
JFrame {
5
// Declare and create a description panel
6
7
8
public static void
main(String[] args) {
9 TextAreaDemo frame =
new
TextAreaDemo();
10
11 frame.setLocationRelativeTo(
null
);
// Center the frame
private
DescriptionPanel descriptionPanel =
new
DescriptionPanel();
create
descriptionPanel
create frame
frame.pack();