Java Swing How to - Dynamically create JCheckBox and add to a JScrollPane








Question

We would like to know how to dynamically create JCheckBox and add to a JScrollPane.

Answer

import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
/*from   ww w .j ava 2 s  .c o  m*/
public class Main {
  JFrame frame = new JFrame();
  JButton jButton1 = new JButton("Add Checkbox");
  JPanel jPanel1 = new JPanel();
  JScrollPane jScrollPane1 = new JScrollPane(jPanel1);

  public Main() {
    jPanel1.setLayout(new GridLayout(0, 2, 10, 10));
    jButton1.addActionListener(e -> {
      JCheckBox cb = new JCheckBox("New CheckBox");
      jPanel1.add(cb);
      jPanel1.revalidate();
      jPanel1.repaint();
    });
    frame.add(jScrollPane1);
    frame.add(jButton1, BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }

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