AbsoluteLayout is not a good solution but with fixed size it should work.
Are you calling revalidate on your panel object after you added checkbox?
As for Q2 you can store added checkboxes in a Vector or HashMap ( depends what logic is involved ) and then you can create custom ActionListener that implements mentioned interface.
What is more that you can pass reference of your panel to your custom ActionListener and within it's actionPerformed use that reference to call methods on the panel which stores vector of your checkboxes.
Here is my quick example of what I am talking about:
package pkg;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
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{
private 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{
private JButton addCheckBox = new JButton("Add CheckBox");
private 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));
this.checkBoxes.add(chBox);
add(chBox);
this.revalidate();
}
}
public class DynamicCheckBoxTest {
/**
* @param args
*/
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);
}
}