I have a program which creates JButtons which are then added to a JPanel with a BoxLayout which is set to place them vertically. Occasionally the first button is intentionally removed from the JPanel. Initially the Buttons are centered correctly and the Buttons are removing successfully as well. The problem is that the remaining buttons then move apart to fill the space. This is not what I would like, instead, I would like them to re-center along the y-axis without moving apart.
I have a Class which extends JPanel. In the constructor the BoxLayout is created.
setPreferredSize(new Dimension(150, 500));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setAlignmentY(CENTER_ALIGNMENT);
Creating the buttons is currently a method in this class:
createButtons(int numButtons){
for (int i=0;i<numButtons;i++) {
add(new JButton());
}
And removal is another method:
removeButton(){
if(getComponentCount()>1){
remove(0);
validate();
repaint();
}
}
Does anybody know how the make the Buttons remain centered along the y-axis without spreading apart to fill the containing panel?
Have you heard of glue in BoxLayouts which uses a invisble component as a filler(glue), which I think should help to keep the buttons centered, see these 2 links: BoxLayout docs and BoxLayout – Filler this site too has some great tutorial on Boxlayout with glue: BoxLayout Glue and this