Search code examples
javaarraysswingjcheckboxitemlistener

Array of JCheckBoxes


i am adding around 10 check boxes in a JFrame , These are added in for loop being iterted on Array , code goes like this

    JFrame f=new JFrame("hello ");
    FlowLayout fl= new FlowLayout();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(300,300);
    f.setVisible(true);
    f.setLayout(fl);

    for (int i=0 ; i<10; i++)
    {

        b[i]=new JCheckBox();
        b[i].setVisible(true);
        b[i].addItemListener(this);
        f.add(b[i]);

    }  /// and so on . 

My Question is when i implement ItemListener will i have to access each of the CheckBox like This
if(b[1].isSelected()) , if(b[2].isSelected()) or there is anyother technique can be used like a loop or something like This .. Thanks in advance


Solution

  • The ItemListener will be invoked with an instance of ItemEvent. This event has a source (EventObject#getSource()), which will be the component which triggered the event, e.g. your JCheckBox.