Java Swing How to - Manage dynamically added JCheckBoxes to JScrollPane








Question

We would like to know how to manage dynamically added JCheckBoxes to JScrollPane.

Answer

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
/*ww w .  ja  v  a 2 s. c  o m*/
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

class AddCheckBoxAction implements ActionListener {
  CheckBoxPanel panel;
  public AddCheckBoxAction(CheckBoxPanel panel) {
    this.panel = panel;
  }
  @Override
  public void actionPerformed(ActionEvent arg0) {
    panel.addNewCheckBox();
  }
}
class CheckBoxAction implements ActionListener {
  int id;
  CheckBoxAction(int id) {
    this.id = id;
  }
  @Override
  public void actionPerformed(ActionEvent arg0) {
    System.out.println("CheckBox " + this.id + " was clicked");
  }
}

class CheckBoxPanel extends JPanel {
  JButton addCheckBox = new JButton("Add CheckBox");
  Vector<JCheckBox> checkBoxes = new Vector<JCheckBox>();
  public CheckBoxPanel() {
    addCheckBox.addActionListener(new AddCheckBoxAction(this));
    add(addCheckBox);
  }

  public void addNewCheckBox() {
    JCheckBox chBox = new JCheckBox("CheckBox " + (this.checkBoxes.size() + 1));
    chBox.addActionListener(new CheckBoxAction(this.checkBoxes.size() + 1));
    checkBoxes.add(chBox);
    add(chBox);
    revalidate();
  }
}
public class Main {
  public static void main(String[] args) {
    CheckBoxPanel chD = new CheckBoxPanel();
    JFrame mainFrame = new JFrame();
    JScrollPane scrollP = new JScrollPane(
        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollP.setViewportView(chD);
    mainFrame.setSize(320, 200);
    mainFrame.getContentPane().add(scrollP);
    
    mainFrame.setVisible(true);
  }
}