Check Boxes
Introduction.
Checkboxes are typically used when the
developer wants the user to select any of the options in a list. For
example, say you are filling out a form that has a list of potential
reasons for wanting to join the website. The checkboxes likely give
a list of what the developer anticipates might be important to potential
members. But it also allows the user to check any or all of the
items listed. The following table contains a list of the constructors that are available for the JCheckBox class. |
Constructor | Description |
JCheckBox(String) | This will put the specified String as a label for the checkbox |
JCheckBox(String, boolean) | This will put the specified String as a label for the checkbox and initialize it as selected if the boolean argument is true |
JCheckBox(Icon) | This will put the specified icon as a label for the checkbox |
JCheckBox(Icon, boolean) | This will put the specified icon as a label for the checkbox and initialize it as selected if the boolean argument is true |
JCheckBox(String, Icon) | This will put the specified String as a label along with the Icon as a label |
JCheckBox(String, Icon, boolean) | This will put the specified String as a label along with the Icon as a label and initialize it as selected if the boolean argument is true |
The other thing we need to consider when making use of
checkboxes is how the program can sense that the user has interacted with
them. To reiterate a previous page we will make use of
ItemListeners. Listing What's Checked. Now we present our first example, an application called CheckedBoxList.java. This program allows the user to check particular check boxes and then gives a list of those that are checked. It makes use of all of the most important methods associated with ItemListeners. |
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CheckedBoxList extends JFrame {
} // ends CheckBoxTest |
The following image represents the GUI. |
The code will be discussed in class. The only
thing that is particularly exotic is the ways it
Both of these have their own sections of code. Changing Font Properties. We are now going to use a program that I modified from Deitel and Deitel that changes the properties of some text based on what the user checks. It's got some fairly clever coding in it. You should call the program CheckBoxTest.java. |
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CheckBoxTest extends JFrame {
} // ends CheckBoxTest |
The following image represents the GUI. |
Notice how the displayed text changes whether it is
italicized and/or bold based on the user selections. The one truly new piece of code uses the setFont method to change its properties. t.setFont(new Font("TimesRoman",valBold + valItalic, 14)); Notice how adding the constants valBold +
valItalic changes the properties. This is because you are actually
adding integer constants that have been configured to accumulate
attributes. |