选择单选按钮时启用和禁用 JCheckbox(或复选框面板)

Enable and disable the JCheckbox (or Checkbox panel) while selecting radio button

我是 JFrame 的新手,我试图启用和禁用 JCheckbox(或)JCheckbox 面板取决于单选按钮选择。

这里:

  1. 如果选择了“是”单选按钮JCheckboxs 需要禁用面板并且 Textbox 应该启用。

  2. 如果选择“否”单选按钮 JCheckboxs 需要启用并且 Textbox 应该禁用。

我可以启用和禁用文本框,但我不知道如何控制JCheckboxs

这是我的代码

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Set;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

public class Test {

  public static void main(String[] args) {
      new Test();
  }

  public Test() {
      EventQueue.invokeLater(new Runnable() {
          @Override
          public void run() {
              JFrame frame = new JFrame();
              frame.add(new TestPane());
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
          }
      });
  }

  public class TestPane extends JPanel {

      private Set<String> selectedValues = new HashSet<>(8);
   //   JPanel panelCheckBox = new JPanel(new WrapLayout(WrapLayout.LEADING));

      public TestPane() {
          setBorder(new EmptyBorder(16, 16, 16, 16));
          setLayout(new GridBagLayout());

          JTextField textField = new JTextField(40);
          
          JPanel panelCheckBox = new JPanel(new WrapLayout(WrapLayout.LEADING));
          //testing start here
            // DisabledPanel disabledPanel = new DisabledPanel(panelCheckBox);
       //   DisabledPanel disable = new DisabledPanel(panelCheckBox);
             //disabledPanel.setEnabled(false);
          
          

          JRadioButton yes = new JRadioButton("yes");
          yes.setSelected(true);
          yes.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  if (yes.isSelected()) {
                      textField.setEnabled(true);
                      panelCheckBox.setEnabled(false);
                      
                  }
              }
          });

          JRadioButton no = new JRadioButton("No");
          no.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  if (no.isSelected()) {
                    textField.setText("");
                      textField.setEnabled(false);
                      
                  }
              }
          });

          ButtonGroup bg = new ButtonGroup();
          bg.add(yes);
          bg.add(no);

          JPanel enterClassPane = new JPanel(new GridBagLayout());
          enterClassPane.setBorder(new TitledBorder(null, "Enetr Your MetaClass", TitledBorder.LEADING, TitledBorder.TOP, null, null));
          enterClassPane.add(yes);
          enterClassPane.add(no);

        //  JPanel panelCheckBox = new JPanel(new WrapLayout(WrapLayout.LEADING));
       //testing start here
         // DisabledPanel disabledPanel = new DisabledPanel(panelCheckBox);
          //disabledPanel.setEnabled(false);
          int numberCheckBox = 10;
          JCheckBox[] checkBoxList = new JCheckBox[numberCheckBox];

          for (int i = 0; i < numberCheckBox; i++) {
              checkBoxList[i] = new JCheckBox("Diagram " + i);
              panelCheckBox.add(checkBoxList[i]);
          
              checkBoxList[i].addActionListener(new ActionListener() {
                  @Override
                  public void actionPerformed(ActionEvent e) {
                    
                      System.out.println("Selected Diagram " + e.getActionCommand());
                      if (e.getSource() instanceof JCheckBox) {
                          JCheckBox cb = (JCheckBox) e.getSource();
                          if (cb.isSelected()) {
                              selectedValues.add(cb.getActionCommand());
                          } else {
                              selectedValues.remove(cb.getActionCommand());
                          }
                      }
                  }
              });
          }

          JPanel classPane = new JPanel(new GridBagLayout());
          classPane.setBorder(new TitledBorder(null, "Enter Meta Class", TitledBorder.LEADING, TitledBorder.TOP, null, null));
          classPane.add(textField);

          JPanel actionsPane = new JPanel(new GridBagLayout());
          JButton btnCancel = new JButton("Cancel");
          btnCancel.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  System.exit(1);
              }
          });
          JButton btnOkay = new JButton("Okay");
          btnOkay.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  //Text field
                  System.out.println(textField.getText());

                  for (String command : selectedValues) {
                      System.out.println(command);
                  }
              }
          });
          actionsPane.add(btnOkay);
          actionsPane.add(btnCancel);

          GridBagConstraints gbc = new GridBagConstraints();
          gbc.insets = new Insets(4, 4, 4, 4);
          gbc.gridwidth = gbc.REMAINDER;
          gbc.fill = gbc.HORIZONTAL;

          add(enterClassPane, gbc);
          add(new JScrollPane(panelCheckBox), gbc);
          add(classPane, gbc);
          add(actionsPane, gbc);
      }
  }

  public class WrapLayout extends FlowLayout {

      private Dimension preferredLayoutSize;

      public WrapLayout() {
          super();
      }
      public WrapLayout(int align) {
          super(align);
      }

      public WrapLayout(int align, int hgap, int vgap) {
          super(align, hgap, vgap);
      }

      @Override
      public Dimension preferredLayoutSize(Container target) {
          return layoutSize(target, true);
      }
      @Override
      public Dimension minimumLayoutSize(Container target) {
          Dimension minimum = layoutSize(target, false);
          minimum.width -= (getHgap() + 1);
          return minimum;
      }

      private Dimension layoutSize(Container target, boolean preferred) {
          synchronized (target.getTreeLock()) {

              int targetWidth = target.getSize().width;
              Container container = target;

              while (container.getSize().width == 0 && container.getParent() != null) {
                  container = container.getParent();
              }

              targetWidth = container.getSize().width;

              if (targetWidth == 0) {
                  targetWidth = Integer.MAX_VALUE;
              }

              int hgap = getHgap();
              int vgap = getVgap();
              Insets insets = target.getInsets();
              int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
              int maxWidth = targetWidth - horizontalInsetsAndGap;

              //  Fit components into the allowed width
              Dimension dim = new Dimension(0, 0);
              int rowWidth = 0;
              int rowHeight = 0;

              int nmembers = target.getComponentCount();

              for (int i = 0; i < nmembers; i++) {
                  Component m = target.getComponent(i);

                  if (m.isVisible()) {
                      Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();

                      //  Can't add the component to current row. Start a new row.
                      if (rowWidth + d.width > maxWidth) {
                          addRow(dim, rowWidth, rowHeight);
                          rowWidth = 0;
                          rowHeight = 0;
                      }

                      //  Add a horizontal gap for all components after the first
                      if (rowWidth != 0) {
                          rowWidth += hgap;
                      }

                      rowWidth += d.width;
                      rowHeight = Math.max(rowHeight, d.height);
                  }
              }

              addRow(dim, rowWidth, rowHeight);

              dim.width += horizontalInsetsAndGap;
              dim.height += insets.top + insets.bottom + vgap * 2;

              Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);

              if (scrollPane != null && target.isValid()) {
                  dim.width -= (hgap + 1);
              }

              return dim;
          }
      }

      private void addRow(Dimension dim, int rowWidth, int rowHeight) {
          dim.width = Math.max(dim.width, rowWidth);

          if (dim.height > 0) {
              dim.height += getVgap();
          }

          dim.height += rowHeight;
      }
  }
}

您需要更改部分代码:

  1. numberCheckBoxcheckBoxList作为全局变量移动到TestPane中,并将numberCheckBox重命名为NUMBER_CHECK_BOX,因为它将成为现在不变,所以你的代码应该是这样的

    public class TestPane extends JPanel {
        private static final int NUMBER_CHECK_BOX = 10;
        JCheckBox[] checkBoxList = new JCheckBox[NUMBER_CHECK_BOX];
    
        ...
    }
    
  2. 现在,创建一个方法来为面板中的每个复选框setEnabled(...)切换

    private void toggleCheckBoxesEnabled(boolean enabled) {
        for (JCheckBox box : checkBoxList) {
            box.setEnabled(enabled);
        }
    }
    
  3. 现在只需在每个按钮中调用它即可 actionListeners

    yes.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (yes.isSelected()) {
                textField.setEnabled(true);
                toggleCheckBoxesEnabled(true);
            }
       }
    });
    
    no.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (no.isSelected()) {
                textField.setText("");
                textField.setEnabled(false);
                toggleCheckBoxesEnabled(false);
            }
        }
    });
    

顺便说一下,别忘了打电话给 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)


How to disable the checkbox at initial itself

要禁用它们,您需要在创建它们的地方禁用 checkboxes

for (int i = 0; i < numberCheckBox; i++) {
    checkBoxList[i] = new JCheckBox("Diagram " + i);
    checkBoxList[i].setEnabled(false); // Add this line
    panelCheckBox.add(checkBoxList[i]);
    
    ...
}