Width and Height in FlowLayout - Java Swing

Java examples for Swing:FlowLayout

Introduction

A FlowLayout tries to place all components into one row, giving them their preferred size.

If all components do not fit into one row, it starts another row.

A FlowLayout calculates the width as the sum of the preferred widths of all components.

A FlowLayout calculates the height as the height of the tallest component in the container.

The following code shows how to use a FlowLayout for the content pane of a JFrame.

It adds three buttons to the content pane.

Demo Code

import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("Flow Layout Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Container contentPane = frame.getContentPane();
    contentPane.setLayout(new FlowLayout());

    for (int i = 1; i <= 3; i++) {
      contentPane.add(new JButton("Button " + i));
    }//  ww w.  j a  v a 2s.co  m

    frame.pack();
    frame.setVisible(true);
  }
}

Related Tutorials