简体   繁体   English

如何检查从29个复选框中选中了哪些jcheckbox

[英]How check which jcheckboxes are checked out of 29 checkbox

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 我的jframe上有29个jcheckbox,用户可以选择多个jcheckbox的组合,我可以检查哪些复选框是使用长嵌套检查的(如果需要使用的话)

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. 但是结合使用29个复选框,我认为我的方法是完全错误的,而他们是执行此操作的更明智的方法。

I need a smart and handy way to perform this, any suggestion / advice/ code is welcomed 我需要一种简便的方法来执行此操作,欢迎任何建议/建议/代码

Thank you 谢谢

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

Put them in a List<JCheckBox> such as an ArrayList<JCheckBox> and then iterate through the list to find the ones that are checked. 将它们放在List<JCheckBox>例如ArrayList<JCheckBox> ,然后遍历列表以查找已检查的对象。

ie,

// 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. 另一方面,如果在选中复选框后需要执行某些操作,则可以始终使用Map<JCheckBox, Runnable>例如HashMap),如果选中此复选框,则运行Runnable。


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

Here is bit flags version: 这是位标记版本:

屏幕截图

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM