1

I want to create check boxes dynamically in java so that whenever a button is pressed a new check box is created and appeared and whenever another button is pressed all the checked boxes are removed. Can anyone help about that?

Up till now i have only the check boxes created manually

cb1=new JCheckBox("Task 1"); 
cb2=new JCheckBox("Task 2"); 
cb3=new JCheckBox("Task 3"); 
cb4=new JCheckBox("Task 4"); 
cb5=new JCheckBox("Task 5"); 
cb6=new JCheckBox("Task 6"); 

addTask= new JButton("Add Task"); 
removeTask= new JButton("Remove Checked"); 

addTask.addActionListener(this); 
removeTask.addActionListener(this);
skaffman
  • 398,947
  • 96
  • 818
  • 769
Fatema Mohsen
  • 175
  • 2
  • 5
  • 11

8 Answers8

3

Lets say that instead of cb1, cb2, cb3 etc you create an ArrayList of JCheckBoxes and create a panel only for checkboxs, not for the buttons. Now, every time you press the add button you create another checkbox, and add it to both panel and ArrayList. When you press the remove button you clear the array list and the panel. The following code is only an example snippet, not a full tested code, but it should give you a direction.

// Up in your code
List<JCheckBox> cbarr = new ArrayList<JCheckBox>();
// The listener code
public void actionPerformed(ActionEvent e) { 
     if (e.getSource() == addTask) // add checkbox
     {
          JCheckBox cb = new CheckBox("New CheckBox");
          cbarr.add(cb);
          cbpanel.add(cb);
     }
     else // remove checkboxs
     {
          cbarr = new ArrayList<JCheckBox>();
          cbpanel.removeAll()
     }
}

EDIT

I am sorry, but I missed the part when you said you want to remove only the checked boxes. This can be done easily by changing the code in the else block:

for (int i = cbarr.size() - 1; i >=0; i--)
{
    JCheckBox cb = cbarr.get(i);
    if (cb.isSelected())
    {
        cbarr.remove(cb);
        cbpanel.remove(cb);
    }
}
MByD
  • 135,866
  • 28
  • 264
  • 277
  • +1 good code. Great for a general solution. I know I am beeing picky, but :)... Probably using removeAll will not always be the case. But if you will assume that in the panel for which you are calling this method you have only your checkboxes you are fine. – Boro Apr 22 '11 at 14:38
  • Thanks, I think I mentioned this solution requires him to create a separate panel. Sometimes it will not fit, but I think those times are pretty rare. – MByD Apr 22 '11 at 14:44
3

//This will surely help you!

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;

    class tester {
      JButton remove;
      JButton appear;
      JCheckBox cb[]=new JCheckBox[10]; 


       tester() {
          buildGUI();
          hookUpEvents();
       }

       public void buildGUI() {
           JFrame fr=new JFrame();
           JPanel p=new JPanel();
           remove=new JButton("remove");
           appear=new JButton("appear");
             for(int i=0;i<10;i++) {
                cb[i]=new JCheckBox("checkbox:"+i);
                cb[i].setVisible(false);
             }
           fr.add(p);
           p.add(remove);
           p.add(appear);
           for(int i=0;i<10;i++) {
             p.add(cb[i]);
           }
           fr.setVisible(true);
           fr.setSize(400,400);
        }

        public void hookUpEvents() {
           remove.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    for(int i=0;i<10;i++) {
                        cb[i].setVisible(false);
                     }
                 }
           });

           appear.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                   for(int i=0;i<10;i++) {
                      cb[i].setVisible(true);
                    }
                }
           });
         }

         public static void main(String args[]) {
             new tester();
         }
        }
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
  • I agree this could help. Though you could have made it a bit nicer, by for example highlight significance of the number 10 in your code (a variable number of checkboxes). Plus other issues connected to limits of the array structure, where @Fatema Mohsen is after a dynamic solution. Anyway it is useful as a starting point. – Boro Apr 22 '11 at 15:59
2

Instead of creating a new variable for each checkbox. Store references to the checkboxes in a list. When you create new check boxes add them to the list. When you want to remove them all, remove them from the GUI and clear the list.

jzd
  • 23,473
  • 9
  • 54
  • 76
  • Many Thanks for the answers but i want to remove only the selected boxes, so i`d check for that before removing them so how could i check for each box in the list? Also how could i specify the position of the boxes so that whenever a box is removed, the box below it will take its place? Thanks in advance – Fatema Mohsen Apr 22 '11 at 14:15
  • @Fatema Mohsen, this is actually very good suggestion it will allow you to always get your hands on your checkboxes independent of what other components you might have in your panel. I would you it. Of course you still have to remove them from the panel. But you instead are iterating over the list directly. +1 to @jzd for this. – Boro Apr 22 '11 at 14:35
2

You should use some Layout Manager, for example GridLayout, for which you can specify, rows or columns to be dynamic by setting them to 0 in the layout constructor.

In actionPerformed method you would add to the panel new checkbox using JPanel.add() method, validate it afterwords and you are done.

About removal you can iterate through list of the components of the panel and call JPanel.remove() method, validate the panel afterwards.

Good luck, Boro.

Boro
  • 7,913
  • 4
  • 43
  • 85
2

When you dynamically add/remove components for a GUI you need to tell the layout manager that changes have been made. YOu do this with code like:

panel.add(....);
panel.revalidate();
panel.repaint();
camickr
  • 321,443
  • 19
  • 166
  • 288
1

This Nested Layout Example has a JButton on the left to Add Another Label. It adds labels in columns of two. The same basic principal could be applied to adding any number of JCheckBox.

To remove them, call Container.removeAll() and call the same methods afterwards to update the GUI.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

All the above solutions are excellent. One alternative though is if you have a significant list of check boxes in a column, Consider instead using a JTable that has a column of check boxes and perhaps a column as a "label". The Oracle Swing JTable tutorial will show you how to do this, but it's simply a matter of extending a DefaultTableModel class and overriding it's getColumnClass method to return Boolean.class for the column with the checkboxes. Then fill the model with Boolean objects. You can then add or remove rows from the model and have the JTable take care of handling the GUI nitty gritty. If you want to try it this way, we can help you with the specifics.

edit 1:
For Example:

edit 2:
add/remove functionality shown

edit 3:
Moved the removeChecked and showAll methods into the model class.

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
public class CheckBoxTable extends JPanel {
   public static final String[] COLUMNS = {"Purchased", "Item"};
   public static final String[] INITIAL_ITEMS = {"Milk", "Flour", "Rice", "Cooking Oil", "Vinegar"}; 
   private CheckBoxDefaultTableModel model = new CheckBoxDefaultTableModel(COLUMNS, 0);
   private JTable table = new JTable(model);
   private JTextField itemTextField = new JTextField("item", 10);

   public CheckBoxTable() {
      JButton addItemBtn = new JButton("Add Item");
      addItemBtn.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            addItemActionPerformed();
         }
      });
      JButton removeCheckedItemsBtn = new JButton("Remove Checked Items");
      removeCheckedItemsBtn.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            removeCheckedItemsActionPerformed();
         }
      });
      JButton showAllBtn = new JButton("Show All");
      showAllBtn.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            showAllActionPerformed();
         }
      });
      itemTextField.addFocusListener(new FocusAdapter() {
         public void focusGained(FocusEvent e) {
            itemTextField.selectAll();
         }
      });
      JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
      btnPanel.add(itemTextField);
      btnPanel.add(addItemBtn);
      btnPanel.add(removeCheckedItemsBtn);
      btnPanel.add(showAllBtn);

      setLayout(new BorderLayout(5, 5));
      add(new JScrollPane(table), BorderLayout.CENTER);
      add(btnPanel, BorderLayout.SOUTH);

      for (int i = 0; i < INITIAL_ITEMS.length; i++) {
         Object[] row = {Boolean.FALSE, INITIAL_ITEMS[i]};
         model.addRow(row);
      }
   }

   private void showAllActionPerformed() {
      model.showAll();
   }

   private void removeCheckedItemsActionPerformed() {
      model.removeCheckedItems();
   }

   private void addItemActionPerformed() {
      String item = itemTextField.getText().trim();
      if (!item.isEmpty()) {
         Object[] row = {Boolean.FALSE, item};
         model.addRow(row);
      }
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("CheckBoxTable");
      frame.getContentPane().add(new CheckBoxTable());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

@SuppressWarnings("serial")
class CheckBoxDefaultTableModel extends DefaultTableModel {
   private List<String> removedItemsList = new ArrayList<String>();

   public CheckBoxDefaultTableModel(Object[] columnNames, int rowCount) {
      super(columnNames, rowCount);
   }

   public void showAll() {
      if (removedItemsList.size() > 0) {
         Iterator<String> iterator = removedItemsList.iterator();
         while (iterator.hasNext()) {
            String next = iterator.next();
            Object[] row = {Boolean.TRUE, next};
            addRow(row);
            iterator.remove();
         }
      }
   }

   @Override
   public Class<?> getColumnClass(int columnNumber) {
      if (columnNumber == 0) {
         return Boolean.class;
      }
      return super.getColumnClass(columnNumber);
   }

   public void removeCheckedItems() {
      int rowCount = getRowCount();
      for (int row = rowCount - 1; row >= 0; row--) {
         if ((Boolean) getValueAt(row, 0)) {
            removedItemsList.add(getValueAt(row, 1).toString());
            removeRow(row);
         }
      }

   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • If I only could +1 more time I would for the example. Store in my StackOverflow project in NetBeans. Thanks :) – Boro Apr 22 '11 at 17:49
  • @Hovercraft Full Of Eels very nice piece of code. @Fatema Mohsen you can easily accept this answer I doubt anyone make you a better example that has it all :) Great stuff. Stored. – Boro Apr 23 '11 at 06:38
  • @Hovercraft Full OfEels ++++1 :) Thank you so much for the great code :) I really appreciate it. – Fatema Mohsen Apr 24 '11 at 18:54
  • @Boro Thank you very much for your coordination :) it was really helpful – Fatema Mohsen Apr 24 '11 at 18:55
0

You can use arrays of collections that contain check box types, initialize data collections for check box names, initialize check boxes and collection arrays, and finally loop through collection arrays and perform logic processing based on whether check box objects are selected or not.

Austin
  • 14
  • 3