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

时间:2014-11-02 18:54:46

标签: java swing jcheckbox

我的jframe上有29个jcheckbox,用户可以选择多个jcheckbox的组合 如果我必须使用

,我可以检查使用长嵌套检查哪些复选框
if(jCheckBox1.isSelected()==true)

依旧......

但是29复选框的组合我认为我的方式是完全错误的,他们是一些更明智的方法。

我需要一种聪明且方便的方式来执行此操作,欢迎任何建议/建议/代码

谢谢

3 个答案:

答案 0 :(得分:0)

不要为每个变量创建单个变量,而是单个数组。例如:

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

答案 1 :(得分:0)

将它们放在List<JCheckBox>中,例如ArrayList<JCheckBox>,然后遍历列表以查找已检查的列表。

即,

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

另一方面,如果选中复选框后需要执行某些操作,则可以始终使用Map<JCheckBox, Runnable>(如HashMap),然后在选中复选框时运行Runnable。 / p>


修改
在评论中发布的代码修改(再次,请避免这样做),对我来说很好:

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

答案 2 :(得分:0)

这是位标志版本:

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