Thursday, 14 May 2015

Checkboxes in Java

Checkboxes are text items with a checkable icon next to them. They're generally used when you want the user to be able to set several options prior to making a decision. You usually don't do anything when a checkbox is checked or unchecked, you usually just read the values of the checkboxes when some other control, such as a button or menu item, is activated. Just in case you do want the code to do something when a box's state changes, checkboxes generate an ACTION_EVENT with the new Checkbox state as the argument after the user clicks on them.

Note
Radio buttons look just like checkboxes, but they are grouped and only one radio button in a group can be checked at any given time. The next section discusses how to implement radio buttons.


The code in Listing 17.18

Listing 17.18. Checkboxes without a bank.


import java.awt.*;

import java.applet.Applet;


public class checkboxes extends Applet
{
    public void init()
    {
        Checkbox box_1, box_2, box_3;

        box_1 = new Checkbox(); 
        box_2 = new Checkbox("this is a labeled checkbox");
        box_3 = new Checkbox("Labeled and checked", null, true);
        add(box_1);
        add(box_2);
        add(box_3);
    }

}

The creator's methods for Checkbox and the key checkbox methods follow.
new Checkbox()
Creates a new checkbox with no label.
new Checkbox(String the_label)
Creates a new checkbox with a label.
new Checkbox(String the_label, CheckboxGroup null, boolean checked?)
Creates a new checkbox that is labeled and checked. The middle argument is used with radio buttons.
setLabel(String the_new_label)
Changes the label of a checkbox.
String getLabel()
Returns the current label as a string.
boolean getState()
Gets the current checkbox state (checked = TRUE).
setState(boolean new_state)
Sets the checkbox state.

No comments:

Post a Comment