Java Swing How to - Have FlowLayout reposition components upon resizing








Question

We would like to know how to have FlowLayout reposition components upon resizing.

Answer

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
/*from   ww  w  .ja  v  a  2  s.  c om*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JFrame {
  JPanel flowPanel = new JPanel(new FlowLayout());

  public Main() {
    setPreferredSize(new Dimension(300, 300));
    getContentPane().setLayout(new BorderLayout());
    
    flowPanel.add(new JLabel("One"));
    flowPanel.add(new JLabel("Two"));
    flowPanel.add(new JLabel("Three"));
    flowPanel.add(new JLabel("Four"));
    flowPanel.add(new JLabel("Five"));

    getContentPane().add(flowPanel, BorderLayout.NORTH);
    addComponentListener(new ComponentAdapter() {
      public void componentResized(ComponentEvent e) {
        Main.this.getContentPane().remove(flowPanel); 
        Main.this.getContentPane().add(flowPanel);
      }
    });
  }

  public static void main(String[] args) {
    final Main frame = new Main();
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}