You can achieve it easily using JPanel#add(component,index)
and JPanel#remove(index)
No need to remove all the component form the container. Simply remove the desired component and add new component at the desired position.
Sample code:
final JPanel panel = new JPanel(new FlowLayout());
for (int i = 0; i < 10; i++) {
panel.add(new JButton(String.valueOf(i)));
}
JButton remove = new JButton("Remove");
remove.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
panel.remove(2);
panel.revalidate();
}
});
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
panel.add(new JButton("21"), 2);
panel.revalidate();
}
});