Java Swing How to - Center a BoxLayout after removing components








Question

We would like to know how to center a BoxLayout after removing components.

Answer

import java.awt.Color;
import java.awt.Component;
// w w w .ja  v  a2 s  .co m
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    panel.setBorder(BorderFactory.createLineBorder(Color.RED));
    BoxLayout mgr = new BoxLayout(panel, BoxLayout.Y_AXIS);
    panel.setLayout(mgr);
    for (int i = 0; i < 5; i++) {
      JButton button = new JButton("Remove Hello World " + (i + 1));
      button.setAlignmentX(Component.CENTER_ALIGNMENT);
      button.addActionListener(e -> {
        panel.remove(button);
        panel.revalidate();
        panel.repaint();
      });
      panel.add(button);
    }
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
  }
}