javaswingjframejcheckbox

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


I'm very new to JFrame, I was trying to enable and disable the JCheckbox (or) JCheckbox panel depends on radio button selection.

Here :

  1. If "Yes" Radio button is selected JCheckboxs panel needs to be disabled and Textbox should be enabled.

  2. If "No" Radio button is selected JCheckboxs needs to be enabled and Textbox should be disabled.

I can enable and disable the textbox but I don't know to control JCheckboxs

Here's my code

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

Solution

  • You will need to change some parts of your code:

    1. Move numberCheckBox and checkBoxList as global variables inside TestPane, and rename numberCheckBox to NUMBER_CHECK_BOX as it will become a constant now, so your code should be looking like this

      public class TestPane extends JPanel {
          private static final int NUMBER_CHECK_BOX = 10;
          JCheckBox[] checkBoxList = new JCheckBox[NUMBER_CHECK_BOX];
      
          ...
      }
      
    2. Now, create a method to toggle setEnabled(...) for each checkbox in the panel

      private void toggleCheckBoxesEnabled(boolean enabled) {
          for (JCheckBox box : checkBoxList) {
              box.setEnabled(enabled);
          }
      }
      
    3. And now just call it inside each of the buttons' 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);
              }
          }
      });
      

    enter image description here enter image description here

    And by the way, don't forget to call frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)


    How to disable the checkbox at initial itself

    To disable them, you'll need to disable the checkboxes where you create them:

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