Saturday, August 24, 2013

JProgressBar

JProgressBar is a component to visually display the progress of a task. The progress bar displays the percentage of the task completed. It starts with an empty rectangle. Then the rectangle is filled in gradually toward the complete state of the task.

Constructors of the JProgressBar class:
-JProgressBar()
creates a progress bar.
-JProgressBar(BoundedRangeModel model)
creates a progress bar with its data are taken from the model.
-JProgressBar(int min, max)
creates a progress bar with the specified minimum and maximum values.
-JProgressBar(int orent,int min,int max)
creates a progress bar with the specified orientatin, minimum and maximum values.

Useful methods of the JProgressBar class:
-getValue():int
returns the current value of the progress bar.
-isIndeterminate():boolean
returns true if the progress bar is indeterminate state.
-setIndeterminate(boolean value):void
allows the progress bar in determinate or indeterminate state.
-setStringPainted(boolean painted):void
Shows or deos not show the string representing the percentage of the work progress.
-setValue(int value):void
sets the current value of the progress bar.

In the example program below, the progress bar is created to show the progress of retrieving available font names from the system. The DefaultRoundedRangleModel class is used to define the current value, extent value, an min and max values of the progress bar. The Thread.sleep(50) delays each progress step 50 milliseconds to ensure the progress is visible.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import javax.swing.BoundedRangeModel;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

class JProgressBarShow extends JFrame{
JLabel lbl;
JProgressBarShow(String title){
setTitle(title);
setSize(500,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new BorderLayout());
setVisible(true);
JPanel p=new JPanel();
p.setLayout(new GridLayout(2,1));
BoundedRangeModel model=new DefaultBoundedRangeModel(0,1,0,100);
String[] fn=fnames();
model.setMinimum(0);
model.setMaximum(fn.length);
model.setExtent(1);
JProgressBar pbar=new JProgressBar(model);
pbar.setForeground(Color.BLUE);
pbar.setStringPainted(true);
p.add(pbar);
lbl=new JLabel("Please wait...");
lbl.setForeground(Color.RED);
p.add(lbl);
contpane.add(p, BorderLayout.NORTH);
validate();
DefaultListModel lmodel=new DefaultListModel();
for(String n:fn){
lmodel.addElement(n);
pbar.setValue(pbar.getValue()+1);
try{
Thread.sleep(50);
}catch(InterruptedException ie){}
}
lbl.setText("Complete");
JList fontlist=new JList(lmodel);
contpane.add(fontlist,BorderLayout.CENTER);
validate();

}

public String[] fnames(){
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
return ge.getAvailableFontFamilyNames();

}



}

public class JFrameSwing {
public static void main(String[] args){
new JProgressBarShow("JProgressBar");
}
}

JProgressBar task in progressing

JProgressBar complete task

JSlider

JSlider is a component that allows you select a value graphically from a range of values. JSlider component generates an change event when the user drags the slider' knob. So you need to implement the ChangeListner interface to receive the event.

Constructors of the JSlider class:
-JSlider()
creates a horizontal slider with the range 0 to 100 and initial value 50.
-JSlider(int orientation)
creates a slider with the specified orientation and the range 0 to 100 and initial value 50.
-JSlider(int min,int max)
creates a slider with the specified min and max values.
-JSlider(int min,int max,int value)
creates a slider with the specified min,max, and initial values.
-JSlider(int orientation,int min,int max,int value)
creates a slider with the specified orientation, min, max, and initial values.

Useful methods of the JSlidder class:
-getValue():int
returns the current value of the slidder.
-setMaximum(int n):void
sets the maximum value to n.
-setMinimum(int n):void
sets the minimum value to n.
-setValue(int n):void
sets the current value to n.

In the example program below, we construct a integer slider that allows the user to selection an integer value graphically. The current value of slide is 0. The min and max values of the slider are 0 and 1000 respectively. The stateChanged method is overridden to get the value of the slider and this value will be used to construct the color object to be applied to the background of the window.
You can set a background color of the JFrame window by using the setBackground method.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

class JSlidderShow extends JFrame implements ChangeListener{
JPanel p;
JSlidderShow(String title){
setTitle(title);
setSize(500,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new BorderLayout());
JSlider slider=new JSlider(JSlider.HORIZONTAL,0,1000,0);
slider.addChangeListener(this);
p=new JPanel();
p.add(slider);
contpane.add(p,BorderLayout.CENTER);
setVisible(true);

}

public void stateChanged(ChangeEvent e){
JSlider sl=(JSlider)e.getSource();
p.setBackground(new Color(sl.getValue()));

}


}

public class JFrameSwing {
public static void main(String[] args){
new JSlidderShow("JSlider");
}
}

JSlider Swing

JSpinner

JSpinner represents a combination of an input field and a ordered list of values. The user is allowed to type value in the field. He/she also can select a value from the ordered list. The Spinner component can generate change event. So you need to receive the event by implementing the ChangeListner interface.

Constructors of the JSpinner class:
-JSpinner()
creates a spinner with an Integer SpinnerNumberModel.
-JSpinner(SpinnerModel model)
creates a spinner with the specified model. The commonly used sub-classes of the SpinnerModel interface are SpinnerNumberModel and SpinnerDateModel.

Useful methods of the JSpinner class:
-commitEdit():void
commits the curretly edited value to the spinner model.
-getValue():Object
returns the current value of the spinner.
-setEditor(JComponent editor):void
sets the specified editor (supporting input formats) to the spinner.
-setModel(SpinnerMode model):void
sets the specified model to the spinner.


Example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

class JSpinnerShow extends JFrame implements ChangeListener{
JLabel lblqty;
JLabel lbldate;
JSpinner numspinner;
JSpinner datespinner;
JSpinnerShow(String title){
setTitle(title);
setSize(500,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new GridLayout(2,1));
JPanel p=new JPanel();
p.setLayout(new GridLayout(2,2));
p.setBorder(BorderFactory.createTitledBorder("Sale Entry"));
SpinnerNumberModel spnummodel=new SpinnerNumberModel(10,1,100,1);
numspinner=new JSpinner(spnummodel);
numspinner.addChangeListener(this);
p.add(new JLabel("Select quantity sold:"));
p.add(numspinner);
Date cdate=new Date();
SpinnerDateModel spdatemodel=new SpinnerDateModel(cdate,null,null,Calendar.DATE);
datespinner=new JSpinner(spdatemodel);
datespinner.setEditor(new JSpinner.DateEditor(datespinner, "dd:MM:yyyy"));
datespinner.addChangeListener(this);
p.add(new JLabel("Select sale date:"));
p.add(datespinner);
contpane.add(p,BorderLayout.CENTER);
JPanel plbl=new JPanel();
plbl.setLayout(new FlowLayout());
lblqty=new JLabel();
lblqty.setForeground(Color.RED);
lbldate=new JLabel();
lbldate.setForeground(Color.RED);
plbl.add(lblqty);
plbl.add(lbldate);
plbl.setBorder(BorderFactory.createTitledBorder("Information"));
contpane.add(plbl);
setVisible(true);

}

public void stateChanged(ChangeEvent e){
JSpinner sp=(JSpinner)e.getSource();
try{
sp.commitEdit();
}catch(ParseException pe){}
if(sp==numspinner)
lblqty.setText("Quantity:"+sp.getValue().toString());
else if(sp==datespinner)
lbldate.setText("Date:"+sp.getValue().toString());
}


}

public class JFrameSwing {
public static void main(String[] args){
new JSpinnerShow("JSpinner");
}
}

JSpinner Swing

In the example program above, the number spinner is created to provide a text field and a selectable list of numbers. The spinner data such as current, min, max, and increment values are defined when the SpinnerNumberModel is created. The second spinner is date spinner to the allow the user to enter a date or select a date from the list.  The SpinnerDateModel object is constructed to provide the current date, lower and upper bound dates, and the size of increase or decrease. By assigning null values to the lower and upper bounds dates, your date spinner will not have lower and upper limit dates. The size of the increase or decrease will be one field of the Calendar class.  It can be one of the followings:

Calendar.ERA
Calendar.YEAR
Calendar.MONTH
Calendar.WEEK_OF_YEAR
Calendar.WEEK_OF_MONTH
Calendar.DAY_OF_MONTH
Calendar.DAY_OF_YEAR
Calendar.DAY_OF_WEEK
Calendar.DAY_OF_WEEK_IN_MONTH
Calendar.AM_PM
Calendar.HOUR
Calendar.HOUR_OF_DAY
Calendar.MINUTE
Calendar.SECOND
Calendar.MILLISECOND

To format the date displays on the text field, you need to set the editor to the date spinner by using the DateEditor sub-class of the JSpinner class. In this example code, the form of the date displays in the text field is dd-MM-yyyy (two-digits day, two-digit month, and four-digit year.

JList

JList represents a list of items. You can select one or a number of items from the list. JList can generate the list selection event so you need to implement the ListSelectionListener interface to receive the event. This interface has a method called valueChanged(ListSelectEvent e) that needs to be overridden. Below are the summary of JList constructors and its useful methods.

Constructors of the JList class:
-JList()
creates an empty list.
-JList(ListModel model)
creates a list with a list mode that maintains the list items.
-JList(Object[] items)
creates a list that its items are taken from an array of items array.
-JList(vector<?> items)
creates a list that its items are taken from the vector items.

Useful methods of the JList class:
-getSelectedIndex():int
returns the index of the selected item.
-getSelectedIndices():int[]
returns the array of selected indices.
-getSelectedValue():Object
returns the selected item.
-getSelectedValues():Object[]
returns the array of selected items.
-isSelectedIndex(int index):boolean
returns true if the item at the specified index is selected.
-setCellRenderer(ListCellRender render):void
specifies the cell render for the list.
-setFixedCellHeight(int h):void
specifies a value to be the height of every cell.
-setFixedCellWidth(int w):void
specifies a value to be the width of every cell.
-setListData(Object[] items):void
specifies the data items of the list.
-setSelectedIndex(int index):void
selects a single cell at the specified index.
-setSelectedIndices(int[] indices):void
selects multiple cells at the indices.
-setSelectedValue(Object item, boolean scroll):void
selects an item from the list.

Other useful methods are not in the JList class. They are in the DefaultListModel class. It is a list model class that implements the ListModel interfaces.
-AddElement(Object item):void
adds an item to end of the list.
-clear():void
removes all items of the list.
-contains(Object item):boolean
Tests whether or not an item is in the list.
-getElementAt(int index):Object
returns the element at the specified index in the list.
-getSize():int
returns the number of items in the list.
-removeElementAt(int index):void
delete the item at the specified index of the list.
-removeElement(Object item):void
delete the specified item of the list.
-toArray():Object[]
converts the list to an array of objects.


Example:
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

class JListShow extends JFrame implements ListSelectionListener{
JLabel lbl;
JListShow(String title){
setTitle(title);
setSize(400,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new GridLayout(1,2));
String[] fname=readAvailableFonts();
DefaultListModel model=new DefaultListModel();
for(String name:fname){
model.addElement(name);
}
JList list=new JList(model);
list.addListSelectionListener(this);
list.setVisibleRowCount(10);
JScrollPane scroll=new JScrollPane(list);
contpane.add(scroll);
lbl=new JLabel();
contpane.add(lbl);
setVisible(true);
}

public void valueChanged(ListSelectionEvent e){
JList lst=(JList)e.getSource();
String selectedFontName=(String)lst.getSelectedValue();
lbl.setText(selectedFontName);
lbl.setFont(new Font(selectedFontName, Font.PLAIN,20));
}

public String[] readAvailableFonts(){
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] f=ge.getAvailableFontFamilyNames();
return f;
}


}

public class JFrameSwing {
public static void main(String[] args){
new JListShow("JList");
}
}

JList Swing

ListCellRenderer interface specifies components that will be used to render the cells of the list (created by JList class). For example, a class that implements the ListCellRender interface can specify labels to render the cells of the list so you are able to apply the font name, font size, text color, and background color, and image icon to the cells of the list as you do with the labels (created by JLabel class).

Example:
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

class ListCellRendererShow extends JFrame implements ListSelectionListener{
JLabel lbl;
ListCellRendererShow(String title){
setTitle(title);
setSize(400,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new GridLayout(1,2));
String[] fname=listDate();
DefaultListModel model=new DefaultListModel();
for(String name:fname){
model.addElement(name);
}
JList list=new JList(model);
list.addListSelectionListener(this);
list.setVisibleRowCount(10);
list.setCellRenderer(new CellRenderer());
JScrollPane scroll=new JScrollPane(list);
contpane.add(scroll);
lbl=new JLabel();
contpane.add(lbl);
setVisible(true);
}

public void valueChanged(ListSelectionEvent e){
JList lst=(JList)e.getSource();
String selectedFontName=(String)lst.getSelectedValue();
lbl.setText(selectedFontName);
lbl.setFont(new Font(selectedFontName, Font.PLAIN,20));
}

public String[] listDate(){
String[] data={"Abandon","Abate","abdomen","babble","baboon","baby"};
return data;
}

class CellRenderer extends JLabel implements ListCellRenderer {
    public CellRenderer() {
        setOpaque(true);
    }

    public Component getListCellRendererComponent(JList list,
                                                  Object value,
                                                  int index,
                                                  boolean isSelected,
                                                  boolean cellHasFocus) {
   
        setText(value.toString());
        setFont(new Font("Tahoma", Font.PLAIN,15));
        Color backcolor;
        Color forecolor;      
        if (isSelected) {
            backcolor = Color.YELLOW;
            forecolor = Color.RED;
            setIcon(new ImageIcon("d:/iconlist.png"));
        } else {
            backcolor = Color.WHITE;
            forecolor = Color.BLACK;
            setIcon(null);
        }
        setBackground(backcolor);
        setForeground(forecolor);      
        return this;
    }
}

}

public class JFrameSwing {
public static void main(String[] args){
new ListCellRendererShow("ListCellRenderer");
}
}

ListCellRender Swing

JComboBox

JComboBox represents a combination of text field and a drop down list. You can select a single item from drop down list. In default, a combo box is not editable. An editable field can be made by using the setEditable(boolean editable) method. Below are the constructors and useful methods of the JComboBox class.

Constructors of the JComboBox class:
-JComboBox(Object[] items)
creates a combo box that its items are taken from an array.
-JComboBox(ComboBoxModel model)
creates a combo box that its items are taken from a model.
-JComboBox(Vector<?> items)
creates a combo box that its items are taken from a vector.

Useful methods of the JComboBox class:
-addItem(Object item):void
adds an item to the combo box.
-getItemAt(int index):Object
gets the item at the specified index.
-getItemCount():int
gets the number of items in the combo box.
-getSelectedIndex():int
gets index of the selected item.
-getSelectedItem():Object
gets the selected item object.
-removeAllItems():void
removes all items in the combo box.
-removeItem(Object item):void
remove the specified item from the combo box.
-removeItemAt(int index): void
removes the item at the specified index from the combo box.
-setSelectedIndex(int index):void
selects the item at the specified index.
-setSelectedItem(Object):void
selects the specified item object.

Example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

class JComboBoxShow extends JFrame implements ItemListener{
JLabel lbl;
JComboBoxShow(String title){
setTitle(title);
setSize(400,300);
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setLayout(new FlowLayout());
String[] lans={"English","Khmer","Chinese","French","Russian","Japanese"};
JComboBox cb=new JComboBox(lans);
cb.addItemListener(this);
JPanel p=new JPanel();
p.setAlignmentY(JPanel.LEFT_ALIGNMENT);
p.setLayout(new GridLayout(3,1));
lbl=new JLabel();
lbl.setForeground(Color.RED);
p.add(new JLabel("Select your language:"));
p.add(cb);
p.add(lbl);
contpane.add(p);
setVisible(true);
}

public void itemStateChanged(ItemEvent e){
JComboBox cb=(JComboBox)e.getSource();
lbl.setText("Selected language: "+cb.getSelectedItem());
}

}

public class JFrameSwing {
public static void main(String[] args){
new JComboBoxShow ("JComboBox");
}
}

JComboBox Swing

In the example above, an array of string languages are defined. This array acts as a data source of the JComboBox component and it is supplied to the JComboBox when its object is created.  To perform an action when the item of the JComboBox is selected, you need to register the ItemListener with it and then override the itemStateChanged method. Simply, when an item of the JComboBox is selected, its text displays in the JLabel, lbl.

JRadioButton

JRadioButton is the implementation of a radio button item that can be selected or deselected. All radio buttons must be placed in the ButtonGroup to allow only one item is selected from the group. A radio button can generate item event so you need to implement the ItemListener interface to receive the event.

Constructors of the JRadioButton class:
-JRadioButton()
creates an empty radio button.
-JRadioButton(String text)
creates a radio button with specified description text.
-JRadioButton(String text, boolean selected)
creates a radio button with specified description text and selection state.
-JRadioButton(Icon icon)
creates a radio button with specified image icon and no text associated.
-JRadioButton(Icon icon, boolean selected)
creates a radio button with specified image icon and selection state.
-JRadioButton(String Text, Icon icon)
creates a radio button with specified image icon and text.
-JRadioButton(String Text, Icon icon, boolean selected)
creates a radio button with specified image icon, text, and selection.

Useful methods of the JRadioButton class:
-getText():String
reads the text of the radio button.
-isSelected(): boolean
determines whether or not the radio button is selected.
-setText(String text): void
sets the text of the radio button.

Example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

class JRadioButtonShow extends JFrame implements ItemListener{
JLabel lbl;
JRadioButtonShow (String title){
setTitle(title);
setSize(400,300);
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
contpane.setBackground(Color.CYAN);
String[] choices={"int x;","float x","integer x;","double x;"};
JPanel p=new JPanel();
p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
contpane.add(new JLabel("How to you declare an integer variable x?"), BorderLayout.NORTH);
for(String ch:choices){
p.add(new JRadioButton(ch));

}
ButtonGroup bg=new ButtonGroup();
for(int i=0;i<p.getComponentCount();i++)
{
JRadioButton rb=(JRadioButton)p.getComponent(i);
rb.addItemListener(this);
bg.add(rb);
}
contpane.add(p,BorderLayout.CENTER);
lbl=new JLabel();
contpane.add(lbl,BorderLayout.SOUTH);
setVisible(true);

}

public void itemStateChanged(ItemEvent e){
JRadioButton rb=(JRadioButton)e.getSource();
if(rb.isSelected())
lbl.setText(rb.getText());
else
lbl.setText(lbl.getText().replaceAll(rb.getText(),""));
}

}

public class JFrameSwing {
public static void main(String[] args){
new JRadioButtonShow ("JRadioButton");
}
}

JRadioButton Swing

JCheckBox

JCheckBox represents a check box item that can be turned on or turned off. You can turn on or turn off a number of items. The JCheckBox component can generate item event so you need to use the ItemListener interface to receive the event. Alternatively, you also can use the AbstractAction class that implements the Action Interface to handle the action event that is generated by the JCheckBox as you can do with JButton.

Constructors of the JCheckBox class:
-JCheckBox()
creates a new checkbox.
-JCheckBox(String text)
creates a new checkbox with specified text.
-JCheckBox(String text, boolean state)
creates a new checkbox with specified text and selection state.
-JCheckBox(Action action)
creates a new checkbox with properties taken from the implementation of the Action interface.
-JCheckBox(Icon icon)
creates a new CheckBox with an image icon.
-JCheckBox(Icon icon, boolean state)
creates a new CheckBox with an image icon and specified selection state.
-JCheckBox(String text,Icon icon)
creates a new checkbox with specified text and image icon.

Useful methods of the JCheckBox class:
-getText():String
returns the text of the checkbox.
-isSelected():boolean
determines whether or not the checkbox is selected.
-setText(String text)
sets the text of the checkbox.

Example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.plaf.basic.BasicBorders;

class JCheckBoxShow extends JFrame implements ItemListener{
JLabel lbl;
JCheckBoxShow(String title){
setTitle(title);
setSize(400,300);
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
String[] hobbies={"Flower arranging","Mountain biking","Card playing","Football watching","Game playing"};
JPanel p=new JPanel();
p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
p.setBorder(new BasicBorders.ButtonBorder(Color.RED,Color.BLACK,Color.GREEN,Color.YELLOW));
contpane.add(new JLabel("What do you do in your free time?"), BorderLayout.NORTH);
for(String h:hobbies){
p.add(new JCheckBox(h));

}
for(int i=0;i<p.getComponentCount();i++)
{
JCheckBox ch=(JCheckBox)p.getComponent(i);
ch.addItemListener(this);
}
contpane.add(p,BorderLayout.CENTER);
lbl=new JLabel();
contpane.add(lbl,BorderLayout.SOUTH);
setVisible(true);

}

public void itemStateChanged(ItemEvent e){
JCheckBox ch=(JCheckBox)e.getSource();
if(ch.isSelected())
lbl.setText(lbl.getText()+" "+ch.getText());
else
lbl.setText(lbl.getText().replaceAll(ch.getText(),""));
}

}

public class JFrameSwing {
public static void main(String[] args){
new JCheckBoxShow("JCheckBox");
}
}

JCheckBox Swing

To get the number of components added to the container, you can use its getComponentCount() method. If you want to visit every component of the container, you will need to use a loop. Each component in the container can be retrieved by using its getComponent(int index) method.