Thursday, July 8, 2010

How to create and use Check Boxes  

0 comments

CheckBox is a unique java control which lets user select one or more options.This control becomes handy where some sort of selection is to be made.I will explain here the CheckBoxes In Java Swings.Which are created using JCheckBox class.

Constructors:-There are five constructors of CheckBox

1.Checkbox() --> Creates a check box with an empty string for its label.

2.Checkbox(String label, boolean state) --> Creates a check box with the specified label and sets the specified state.

3.Checkbox(String label) --> Creates a check box with the specified label.

4.Checkbox(String label, boolean state, CheckboxGroup group) --> Constructs a Checkbox with the specified label, set to the specified state, and in the specified check box group.

5.Checkbox(String label, CheckboxGroup group, boolean state) --> Creates a check box with the specified label, in the specified check box group, and set to the specified state.

Example:-This simple swing example illustrates how checkboxes are added.

//test.java

import javax.swing.*;

public class test{
public static void main(String[] args){
JFrame frame = new JFrame("Check Box Frame");
JCheckBox chkop1 = new JCheckBox("option 1");
JCheckBox chkop2 = new JCheckBox("option 2");
JCheckBox chkop3 = new JCheckBox("option 3");
JPanel panel=new JPanel();
panel.add(chkop1);
panel.add(chkop2);
panel.add(chkop3);
frame.getContentPane().add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Selecting Checkboxes:-In this example the checkboxes are default selected using setSelected(boolean state) method of JCheckBox class.

//test1.java

import javax.swing.*;

public class test{
public static void main(String[] args){
JFrame frame = new JFrame("Check Box Frame");
JCheckBox chkop1 = new JCheckBox("option 1");
chkop1.setSelected(true);
JCheckBox chkop2 = new JCheckBox("option 2");
chkop2.setSelected(true);
JCheckBox chkop3 = new JCheckBox("option 3");
JPanel panel=new JPanel();
panel.add(chkop1);
panel.add(chkop2);
panel.add(chkop3);
frame.getContentPane().add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}


Other useful methods:-

setLabel() :-Sets Label as provided string to this CheckBox.
getLabel() :-Returns Label of CheckBox.
addItemListener() :-Only ItemListeners can be added to CheckBox control for event handling purposes.

What next?

You can also bookmark this post using your favorite bookmarking service:

Related Posts by Categories



Extension Factory Builder