Fatema Mohsen
Fatema Mohsen

Reputation: 175

Dynamic check boxes in java

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);

Upvotes: 1

Views: 13658

Answers (8)

Austin
Austin

Reputation: 14

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.

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

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);
         }
      }

   }
}

Upvotes: 1

MByD
MByD

Reputation: 137292

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);
    }
}

Upvotes: 3

Suhail Gupta
Suhail Gupta

Reputation: 23216

//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();
         }
        }

Upvotes: 3

camickr
camickr

Reputation: 324108

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();

Upvotes: 2

Andrew Thompson
Andrew Thompson

Reputation: 168825

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.

Upvotes: 1

Boro
Boro

Reputation: 7943

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.

Upvotes: 2

jzd
jzd

Reputation: 23629

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.

Upvotes: 2

Related Questions