Page 686 - Introduction to Programming with Java: A Problem Solving Approach
P. 686

                652 Chapter 16 GUI Programming Basics
• border appearance • tool tips
• focus
For detailed information on the above features, look up the JComponent class on Sun’s Java API Web site.
16.6 JLabel Component User Interface
The JLabel component doesn’t do much. It simply displays a specified single line of text. It’s considered to be a read-only component because the user can read it, but the user cannot interact with it.
Normally, the JLabel component displays a single line of text, not multiple lines. If you want to dis- play multiple lines, use the JTextArea component, which is covered in the next chapter.
Implementation
To create a JLabel object, call the JLabel constructor like this: JLabel <JLabel-reference> = new JLabel(<label-text>);
The label-text is the text that appAearps ian tgheoJLabPelDcFompoEnent.hIfathenlacbeel-terxt argument contains a new- line character, \n, it’s ignored (remember, the JLabel component only displays a single line of text). If the label-text argument is omitted, then the JLabel component displays nothing. Why instantiate an empty label? So you can fill it in later on with text that’s dependent on some condition.
To add a JLabel object to your JFrame window, use this syntax: add(<JLabel-reference>);
The JLabel class needs the javax.swing package, but that should be available already, since it’s needed for the JFrame class.
Methods
The JLabel class, like all the GUI component classes, has quite a few methods. We’ll just mention two of them—the getText and setText accessor and mutator methods. Here are their API headings and descriptions:
public String getText()
Returns the label’s text.
public void setText(String text)
Assigns the label’s text. Note that the programmer can update the label’s text even though the user cannot.
      -
t
e
ec
o
o
p
p
t
t
i
i
o
o
n
na
al
l
          J
-r
J
L
La
a
b
b
e
e
l
l
r
e
ef
f
e
er
re
en
nc
c
  co
om
me
e
s
sf
fr
r
o
o
m
m
t
th
h
e
ea
a
b
bo
ov
v
e
e
i
in
n
i
it
ti
ia
al
l
i
iz
za
a
t
ti
io
o
n
n
s
s
t
t
a
a
t
t
e
em
me
en
n
t
   684   685   686   687   688