Checkbox
The Checkbox
is a general purpose way to record a true
or false
state. When several checkboxes are associated in a CheckboxGroup
(CheckboxGroup), only one can be selected at a time; selecting each Checkbox
causes the previous selection to become deselected. The CheckboxGroup
is Java's way of offering the interface element known as radio buttons or a radio box. When you create a Checkbox
, you decide whether to place it into a CheckboxGroup
by setting the proper argument in its constructor.
Every Checkbox
has both a label and a state, although the label could be empty. You can change the label based on the state of the Checkbox
. Figure 9.4 shows what several Checkbox
components might look like. The two on the left are independent, while the five on the right are in a CheckboxGroup
. Note that the appearance of a Checkbox
varies quite a bit from platform to platform. However, the appearance of a CheckboxGroup
is always different from the appearance of an ungrouped Checkbox
, and the appearance of a checked Checkbox
is different from an unchecked Checkbox
.
Figure 9.4: Two separate checkboxes and a CheckboxGroup
Checkbox Methods
Constructors- public Checkbox ()
- This constructor for
Checkbox
creates a new instance with no label or grouping. The initial state of the item isfalse
. A checkbox doesn't necessarily need a label; however, a checkbox without a label might be confusing, unless it is being used as a column in a table or a spreadsheet. - public Checkbox (String label)
- The second constructor creates a new
Checkbox
with a label oflabel
and no grouping. The initial state of the item isfalse
. If you want a simple yes/no choice and plan to make no the default, use this constructor. If theCheckbox
will be in a group or you want its initial value to betrue
, use the next constructor. - public Checkbox (String label, boolean state)
- This constructor allows you to specify the
Checkbox
's initial state. With it you create aCheckbox
with a label oflabel
and an initial state ofstate
. - public Checkbox (String label, boolean state, CheckboxGroup group)
public Checkbox (String label, CheckboxGroup group, boolean state) - The final constructor for
Checkbox
is the most flexible. With this constructor you create aCheckbox
with a label oflabel
, aCheckboxGroup
ofgroup
, and an initial state ofstate
. Ifgroup
isnull
, theCheckbox
is independent.In Java 1.0, you created an independent
Checkbox
with an initial value oftrue
by usingnull
as the group:Checkbox cb = new Checkbox ("Help", null, true)
The shape of the
Checkbox
reflects whether it's in aCheckboxGroup
or independent. On Microsoft Windows, grouped checkboxes are represented as circles. On a UNIX system, they are diamonds. On both systems, independent checkboxes are squares.
- public String getLabel ()
- The
getLabel()
method retrieves the current label on theCheckbox
and returns it as aString
object. - public synchronized void setLabel (String label)
- The
setLabel()
method changes the label of theCheckbox
tolabel
. If the new label is a different size than the old one, you have tovalidate()
the container after the change to ensure the entire label will be seen.
A state of true
means the Checkbox
is selected. A state of false
means that the Checkbox
is not selected.
- public boolean getState ()
- The
getState()
method retrieves the current state of theCheckbox
and returns it as a boolean. - public void setState (boolean state)
- The
setState()
method changes the state of theCheckbox
tostate
. If theCheckbox
is in aCheckboxGroup
andstate
is true, the other items in the group become false.
- public Objects[] getSelectedObjects ()
- The
getSelectedObjects()
method returns theCheckbox
label as a one-elementObject
array if it is currently selected, ornull
if theCheckbox
is not selected. Because this method is part of theItemSelectable
interface, you can use it to look at the selected items in aChoice
,List
, orCheckbox
.
This section lists methods that you issue to Checkbox
to affect its relationship to a CheckboxGroup
. Methods provided by the CheckboxGroup
itself can be found later in this chapter.
- public CheckboxGroup getCheckboxGroup ()
- The
getCheckboxGroup()
method returns the currentCheckboxGroup
for theCheckbox
. If theCheckbox
is not in a group, this method returnsnull
. - public void setCheckboxGroup (CheckboxGroup group)
- The
setCheckboxGroup()
method allows you to insert aCheckbox
into a differentCheckboxGroup
. To make theCheckbox
independent, pass agroup
argument ofnull
. The method sets everyCheckbox
in the originalCheckboxGroup
tofalse
(cb.getCheckboxGroup().setCurrent(null)
), then theCheckbox
is added to the new group without changing any values in the new group.Checkbox
components take on a different shape when they are in aCheckboxGroup
. If the checkbox was originally not in aCheckboxGroup
, the shape of the checkbox does not change automatically when you put it in one withsetCheckboxGroup()
. (This also holds when you remove aCheckbox
from aCheckboxGroup
and make it independent or vice versa.) In order for theCheckbox
to look right once added togroup
, you need to destroy and create (removeNotify()
andaddNotify()
, respectively) theCheckbox
peer to correct the shape. Also, it is possible to get multiple trueCheckbox
components ingroup
this way, since the newCheckboxGroup
's current selection does not get adjusted. To avoid this problem, make sure it is grouped properly the first time, or be sure to clear the selections with a call togetCheckboxGroup().setCurrent(null)
.
- public synchronized void addNotify ()
- The
addNotify()
method will create theCheckbox
peer in the appropriate shape. If you override this method, callsuper.addNotify()
first, then add your customizations for the new class. You will then be able to do everything you need with the information about the newly created peer. - protected String paramString ()
- When you call the
toString()
method ofCheckbox
, the defaulttoString()
method ofComponent
is called. This in turn callsparamString()
which builds up the string to display. At theCheckbox
level, the label (if non-null) and the state of the item are appended. Assuming the DialogCheckbox
in Figure 9.4 was selected, the results would be:
java.awt.Checkbox[85,34,344x32,label=Dialog,state=true]
Checkbox Events
The primary event for a Checkbox
occurs when the user selects it. With the 1.0 event model, this generates an ACTION_EVENT
and triggers the action()
method. Once the Checkbox
has the input focus, the various keyboard events can be generated, but they do not serve any useful purpose because the Checkbox
doesn't change. The sole key of value for a Checkbox
is the spacebar. This may generate the ACTION_EVENT
after KEY_PRESS
and KEY_RELEASE
; thus the sequence of method calls would be keyDown()
, keyUp()
, and then action()
.
With the version 1.1 event model, you register an ItemListener
with the method addItemListener()
. Then when the user selects the Checkbox
, the method ItemListener.itemStateChanged()
is called through the protected Checkbox.processItemEvent()
method. Key, mouse, and focus listeners are registered through the Component
methods of addKeyListener()
, addMouseListener()
, and addFocusListener()
, respectively. Action
- public boolean action (Event e, Object o)
- The
action()
method for aCheckbox
is called when the user selects it.e
is theEvent
instance for the specific event, whileo
is the opposite of the old state of the toggle. If theCheckbox
wastrue
when it was selected,o
will befalse
. Likewise, if it wasfalse
,o
will betrue
. This incantation sounds unnecessarily complex, and for a singleCheckbox
, it is:o
is just the new state of theCheckbox
. The following code usesaction()
with a singleCheckbox
.public boolean action (Event e, Object o) { if (e.target instanceof Checkbox) { System.out.println ("Checkbox is now " + o); } return false; }
On the other hand, if the
Checkbox
is in aCheckboxGroup
,o
is still the opposite of the old state of the toggle, which may or may not be the new state of theCheckbox
. If theCheckbox
is initiallyfalse
,o
will betrue
, and theCheckbox
's new state will betrue
. However, if theCheckbox
is initiallytrue
, selecting theCheckbox
doesn't change anything because oneCheckbox
in the group must always betrue
. In this case,o
isfalse
(the opposite of the old state), though theCheckbox
's state remainstrue
.Therefore, if you're working with a
CheckboxGroup
and need to do something once when the selection changes, perform your action only wheno
is true. To find out whichCheckbox
was actually chosen, you need to call thegetLabel()
method for the target of evente
. (It would be nice ifo
gave us the label of theCheckbox
that was selected, but it doesn't.) An example of this follows:public boolean action (Event e, Object o) { if (e.target instanceof Checkbox) { System.out.println (((Checkbox)(e.target)).getLabel() + " was selected."); if (new Boolean (o.toString()).booleanValue()) { System.out.println ("New option chosen"); } else { System.out.println ("Use re-selected option"); } } return false; }
One other unfortunate twist of CheckboxGroup
: it would be nice if there was some easy way to find out about checkboxes that change state without selection--for example, if you could find out which Checkbox
was deselected when a new Checkbox
was selected. Unfortunately, you can't, except by keeping track of the state of all your checkboxes at all times. When a Checkbox
state becomes false
because another Checkbox
was selected, no additional event is generated, in either Java 1.0 or 1.1. Keyboard
Checkbox
es are able to capture keyboard-related events once the Checkbox
has the input focus, which happens when it is selected. If you can find a use for this, you can use keyDown()
and keyUp()
. For most interface designs I can think of, action()
is sufficient. A possible use for keyboard events is to jump to other Checkbox
options in a CheckboxGroup
, but I think that is more apt to confuse users than help.
- public boolean keyDown (Event e, int key)
- The
keyDown()
method is called whenever the user presses a key while theCheckbox
has the input focus.e
is theEvent
instance for the specific event, whilekey
is the integer representation of the character pressed. The identifier for the event (e.id
) forkeyDown()
could be eitherKEY_PRESS
for a regular key orKEY_ACTION
for an action-oriented key (i.e., arrow or function key). There is no visible indication that the user has pressed a key over the checkbox. - public boolean keyUp (Event e, int key)
- The
keyUp()
method is called whenever the user releases a key while theCheckbox
has the input focus.e
is theEvent
instance for the specific event, whilekey
is the integer representation of the character pressed. The identifier for the event (e.id
) forkeyUp()
could be eitherKEY_RELEASE
for a regular key orKEY_ACTION_RELEASE
for an action-oriented key (i.e., arrow or function key).keyUp()
may be used to determine how longkey
has been pressed.
Ordinarily, the Checkbox
component does not reliably trigger any mouse events. Focus
Ordinarily, the Checkbox
component does not reliably trigger any focus events. Listeners and 1.1 event handling
With the 1.1 event model, you register listeners, and they are told when the event happens.
- public void addItemListener(ItemListener listener)
- The
addItemListener()
method registerslistener
as an object interested in being notified when anItemEvent
passes through theEventQueue
with thisCheckbox
as its target. Then, thelistener.itemStateChanged()
method will be called. Multiple listeners can be registered. - public void removeItemListener(ItemListener listener)
- The
removeItemListener()
method removeslistener
as a interested listener. If listener is not registered, nothing happens. - protected void processEvent(AWTEvent e)
- The
processEvent()
method receives everyAWTEvent
with thisCheckbox
as its target.processEvent()
then passes it along to any listeners for processing. When you subclassCheckbox
, overridingprocessEvent()
allows you to process all events yourself, before sending them to any listeners. In a way, overridingprocessEvent()
is like overridinghandleEvent()
using the 1.0 event model.If you override
processEvent()
, remember to callsuper.processEvent(e)
last to ensure that regular event processing can occur. If you want to process your own events, it's a good idea to callenableEvents()
(inherited fromComponent
) to ensure that events are delivered even in the absence of registered listeners. - protected void processItemEvent(ItemEvent e)
- The
processItemEvent()
method receives everyItemEvent
with thisCheckbox
as its target.processItemEvent()
then passes it along to any listeners for processing. When you subclassCheckbox
, overridingprocessItemEvent()
allows you to process all events yourself, before sending them to any listeners. In a way, overridingprocessItemEvent()
is like overridingaction()
using the 1.0 event model.If you override
processItemEvent()
, remember to call the methodsuper.processItemEvent(e)
last to ensure that regular event processing can occur. If you want to process your own events, it's a good idea to callenableEvents()
(inherited fromComponent
) to ensure that events are delivered even in the absence of registered listeners.