Academic Java    Java Tutorial  >  Swing  >  FlowLayout

FlowLayout Example

Java FlowLayout EXAMPLE output A layout manager is associated with a container and controls the way components in the container are laid out, typically their size and position.

The layout manager FlowLayout lays its components out left to right and wraps them below if there is insufficient horizontal room for them all.

In the FlowLayout example, by dragging sides or corners of the displayed frame you will witness the layout manager at work.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// FlowLayout Example
import java.awt.*;
import javax.swing.*;

class FlowLayoutExample {

   public static void main(String[] args) {

      JFrame frame = new JFrame();
      Container cp = frame.getContentPane();
      cp.setLayout(new FlowLayout());

      for(int i=0;i<5;++i) cp.add(new JButton("button "+i));

      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

10 The method setLayout() is invoked for the frame's content pane.
The parameter of the call is an instance of the particular layout manager to be associated with the container.