Java Reference
In-Depth Information
//register the item listener to the check boxes
boldCB.addItemListener(
this
);
italicCB.addItemListener(
this
);
//add the check boxes to the pane
c.add(boldCB);
c.add(italicCB);
}
To specify the font and style of the text, we use two
int
variables:
intBold
and
intItalic
. These variables are set to
Font.PLAIN
when the check boxes are not
checked. They are set to
Font.BOLD
and
Font.ITALIC
, respectively, if the correspond-
ing check boxes are checked. To create bold and italic fonts, you simply add the values of
the variables
bold
and
italic
. In other words, you can create desired fonts by just using
intBold + intItalic
as the style value. Note that because
Font.PLAIN
has a value of
zero,
Font.PLAIN + Font.PLAIN
remains
Font.PLAIN
. The
paint
method can be used
to set the color and font, and to display the welcome message. The definition of the
method
paint
can be written as follows:
public void
paint(Graphics g)
{
super
.paint(g);
g.setColor(Color.red);
g.setFont(
new
Font("Courier", intBold + intItalic, 24));
g.drawString("Welcome to Java Programming", 30, 30);
}
To make the program respond to the events generated by the check boxes, next we write
the definition of the method
itemStateChanged
. As shown earlier, the method
itemStateChanged
has one parameter,
e
,ofthetype
ItemEvent
. Because there are
two check boxes, we use the method
getSource
to identify the box generating the event.
The expression:
e.getSource() == boldCB
is
true
if the check box associated with
boldCB
generated the event. Similarly, the
expression:
e.getSource() == italicCB
is
true
if the check box associated with
italicCB
generated the event.
After identifying the check box that generated the event, we determine whether the user
selected or deselected the check box. For this, we use the method
getStateChange
of
the
class
ItemEvent
that returns either the constant
ItemEvent.SELECTED
or the
constant
ItemEvent.DESELECTED
, which are defined in the
class
ItemEvent
. For
example, the expression:
e.getStateChange() == ItemEvent.SELECTED
is
true
if the event
e
corresponds to selecting the check box.
Search WWH ::
Custom Search