-1

I created dynamic JCheckBox, and I don't know how to get their value when I check it.

When I click the checkbox I want to get value and put them to SQL query.

like : query = select checkbox1, checkbox2 from table

This is my dynamic checkbox code:

roll[K] = new JCheckBox();
        roll[K].setText(metaData.getColumnLabel(columnIndex));
        roll[K].setBounds(X,Y,150,30);
        Y = Y+30;
        Rectangle r = jPanel3.getBounds();
        int h=r.height;
        if (Y>=h-50){
            Y=0;
            X=X+200;
       }
   jPanel3.add(roll[K]);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

1 Answers1

0

You can set checkbox item listener like this

roll[K].setActionCommand(Integer.toString(k));
  roll[K].addItemListener(new ItemListener() {

      public void itemStateChanged(ItemEvent e) {
        //this is not necessary and depends upon you, how do u want 
        // use this
        int id = Integer.parseInt(Integer.getSource().getActionCommand())
         //can apply switch case on ID to take appropriate action based on ID
         if (e.getStateChange() == 1) 
               System.out.println("Checked");
         else
               System.out.println("un-Checked");

      }
    });
Harsh kurra
  • 1,094
  • 1
  • 9
  • 19
  • because you are adding them in loop i think `roll[K]` it signify the loop? if you can avoid loop its better otherwise you can associate the command id with your check box and compare command ID in listener – Harsh kurra Jul 17 '19 at 07:27
  • i got error in this code : int id = Integer.parseInt(Integere.getSource().getActionCommand()); – Asrul Paelori Ahmad Jul 17 '19 at 09:28
  • It should work now, if not then there must be some typo problem because I have written this code directly here which you can identify easily – Harsh kurra Jul 30 '19 at 14:22