Skip to Content
Learning Java, 4th Edition
book

Learning Java, 4th Edition

by Patrick Niemeyer, Daniel Leuck
June 2013
Beginner
1007 pages
33h 32m
English
O'Reilly Media, Inc.
Content preview from Learning Java, 4th Edition

FlowLayout

FlowLayout is a simple layout manager that tries to arrange components at their preferred sizes, from left to right and top to bottom in the container. A FlowLayout can have a specified row justification of LEFT, CENTER, or RIGHT and a fixed horizontal and vertical padding. By default, a flow layout uses CENTER justification, meaning that all components are centered within the area allotted to them. FlowLayout is the default for JPanels.

The following example adds five buttons to the content pane of a JFrame using the default FlowLayout:

    //file: Flow.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    public class Flow extends JPanel {

      public Flow() {
        // FlowLayout is default layout manager for a JPanel
        add(new JButton("One"));
        add(new JButton("Two"));
        add(new JButton("Three"));
        add(new JButton("Four"));
        add(new JButton("Five"));
      }

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

        frame.setSize(400, 75);
        frame.setLocation(200, 200);
        Flow flow = new Flow();
        frame.setContentPane(flow);
        frame.setVisible(true);
      }
    }

The result is shown in Figure 19-2.

A flow layout

Figure 19-2. A flow layout

Try resizing the window. If it is made narrow enough, some of the buttons will spill over to a second or third row.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Learning Java, 5th Edition

Learning Java, 5th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan

Publisher Resources

ISBN: 9781449372477Errata PageSupplemental Content