JCheckBox

JCheckBox components are used to represent "binary" choices (on or off, yes or no, true or false). They generate two kinds of events when selected: ActionEvent and ItemEvent. The former is less useful because it does not indicate what state the checkbox is in. To retrieve that information you have to: The example at the right demonstrates the ItemEvent approach. To get the text (or label) of the checkbox you: To get the "state" of the checkbox you evaluate the return value of a call to getStateChange(). It will return either ItemEvent.SELECTED or ItemEvent.DESELECTED.

Notice the comments after each import statement. They document which packages supply which classes and interfaces to the compiler.

The default layout for JFrame's content pane is BorderLayout. When the panel of checkboxes is added to the content pane it is left-justified. The line

   frame.getContentPane().setLayout( new FlowLayout() );
causes the checkboxes to be centered in the content pane.

Notice that a single "object reference" variable is being used to create each of the JCheckBox components. When the checkbox is added to the panel, the panel object makes its own copy of the checkbox object reference. Once a second reference to the checkbox object is established, the first reference may then be used to create a new object. The garbage collector will cause an object to go away only when no references remain to the object.

[Reference: Topley, pp583-590]