0

I have 29 jcheckbox on my jframe, user may select combination of multiple jcheckbox I can check which are checkboxes are check using a long nest if where I have to use

if(jCheckBox1.isSelected()==true)

and so on....

but combination of 29 checkbox I think the way I am is completely wrong and their is some smarter way to do this.

I need a smart and handy way to perform this, any suggestion / advice/ code is welcomed

Thank you

user3599755
  • 93
  • 3
  • 11
  • You could have an array of `JCheckBox`, loop through the array and perform what you want when you come across a selected box. `for(int i = 0; i < array.length; i++) if(array[i].isSelected) { JCheckBox selectedBox = array[i]; }`, you could then use `selectedBox` to do what you want – Vince Nov 02 '14 at 19:00
  • If one of the answers belowed helped you, please choose an accepted answer. If not, please update us on the problems you are having – Vince Nov 13 '14 at 16:04

3 Answers3

1

Put them in a List<JCheckBox> such as an ArrayList<JCheckBox> and then iterate through the list to find the ones that are checked.

i.e.,

// assuming a List<CheckBox> called checkBoxList
for (JCheckBox checkBox : checkBoxList) {
   if (checkBox.isSelected()) {
      String actionCommand = checkBox.getActionCommand();
      // do something here for that checkBox
   }
}

If on the other hand you need to perform certain actions when a check box has been checked, you could always use a Map<JCheckBox, Runnable> such as a HashMap, and then run the Runnable if the check box is selected.


Edit
A modification of your code posted in the comment (again, please avoid doing that), works fine for me:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

@SuppressWarnings("serial")
public class CheckBoxFun extends JPanel {

   // the list should be a class field, not a local variable
   private List<JCheckBox> checkboxes = new ArrayList<JCheckBox>();

   public CheckBoxFun() {
      JPanel checkBoxPanel = new JPanel();
      checkBoxPanel.setLayout(new GridLayout(3, 3));
      checkBoxPanel.setBorder(BorderFactory.createTitledBorder("Check boxes"));
      JCheckBox checkbox;
      String labels[] = { "jCheckBox1", "jCheckBox2", "jCheckBox3",
            "jCheckBox4", "jCheckBox5", "jCheckBox6", "jCheckBox7",
            "jCheckBox8", "jCheckBox9" };
      for (int i = 0; i < labels.length; i++) {
         checkbox = new JCheckBox(labels[i]);
         checkboxes.add(checkbox);
         checkBoxPanel.add(checkbox);
      }

      JButton checkBoxStatusBtn = new JButton(new CheckBoxStatusAction());
      JPanel buttonPanel = new JPanel();
      buttonPanel.add(checkBoxStatusBtn);

      setLayout(new BorderLayout());
      add(checkBoxPanel, BorderLayout.CENTER);
      add(buttonPanel, BorderLayout.PAGE_END);
   }

   private class CheckBoxStatusAction extends AbstractAction {
      public CheckBoxStatusAction() {
         super("Check CheckBoxes");
         putValue(MNEMONIC_KEY, KeyEvent.VK_C);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         for (JCheckBox checkBox : checkboxes) {
            if (checkBox.isSelected()) {
               System.out.println("Check Box Selected: " + checkBox.getActionCommand());
            }
         }
      }
   }


   private static void createAndShowGui() {
      CheckBoxFun mainPanel = new CheckBoxFun();

      JFrame frame = new JFrame("CheckBoxFun");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • I added following code but checkbox are not displayed `JCheckBox checkbox; List checkboxes = new ArrayList(); String labels[] = {"jCheckBox1", "jCheckBox2", "jCheckBox3", "jCheckBox4", "jCheckBox5", "jCheckBox6","jCheckBox7","jCheckBox8","jCheckBox9"}; for (int i = 0; i < labels.length; i++) { { checkbox= new JCheckBox(labels[i]); checkboxes.add(checkbox); jPanel2.add(checkbox); }` – user3599755 Nov 02 '14 at 19:51
  • @user3599755: Please don't post code in comments since it loses its formatting making it unreadable. Instead, post any new code to the bottom of your original question by [editing your question](http://stackoverflow.com/posts/26703060/edit). – Hovercraft Full Of Eels Nov 02 '14 at 20:19
  • @user3599755: please see edit to my answer to see an example runnable program that uses your code. – Hovercraft Full Of Eels Nov 02 '14 at 20:56
  • Ok I understand your way, can I use your code in Netbeans if I simply put a jPanel2 on jPanel1 and jPanel is on Jframe. And finally use your code for putting the checkboxes on jPanel2 – user3599755 Nov 03 '14 at 07:14
0

Don't create a single variable for each of them but a single array. For example:

String boxesNames = new String[] { .... };
JCheckBox boxes = new JCheckBox[boxesNames.length];

for (int i = 0; i < boxes.length; ++i)
  boxesNames = new JCheckBox(boxesNames[i]);

void actionPerformed(ActionEvent e)
{
  for (int i = 0; i < boxes.length; ++i)
    if (boxes[i] == e.getSource())
    {
      // do whatever you want, store them in a set, set a bit in a bit mask etc
    }
}
Jack
  • 131,802
  • 30
  • 241
  • 343
0

Here is bit flags version:

screenshot

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

public final class BitFlagCheckBoxTest {
  private int status = 0b111000111;
  private final JLabel label = new JLabel(print(status));
  public JComponent makeUI() {
    JPanel p = new JPanel();
    for (int i = 0; i < 30; i++) {
      final int f = 1 << i;
      JCheckBox c = new JCheckBox(new AbstractAction(Integer.toString(i)) {
        @Override public void actionPerformed(ActionEvent e) {
          status = ((JCheckBox) e.getSource()).isSelected() ? status | f
                                                            : status ^ f;
          label.setText(print(status));
        }
      });
      c.setSelected((status & f) != 0);
      p.add(c);
    }
    JPanel pnl = new JPanel(new BorderLayout());
    pnl.add(label, BorderLayout.NORTH);
    pnl.add(p);
    return pnl;
  }
  private String print(int i) {
    return String.format(
        "0b%30s", Integer.toBinaryString(i)).replaceAll(" ", "0");
  }
  public static void main(String... args) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() {
        createAndShowGUI();
      }
    });
  }
  public static void createAndShowGUI() {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.getContentPane().add(new BitFlagCheckBoxTest().makeUI());
    f.setSize(320, 240);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}
aterai
  • 9,658
  • 4
  • 35
  • 44