xhtml
 

Flow Layout

Suppose that border layout isn't good enough, say because you want five buttons in a row.  What choices do you have?  One is to change the layout manager used by the frame:

      frame.setLayout(new FlowLayout());
      frame.add(button1);
      ...

Another is to put the buttons inside another container, and then put that container inside the frame as its only (central) component:

RowOfButtons.java
...
JPanel row = new JPanel();
JButton button1 = new JButton("One");
...
row.add(button1);
...
frame.add(row);
...

As usual, when you run the program, check what happens when the window is resized.

A JPanel is the most commonly used internal container.  It's default layout manager is flow layout which is where you can add as many components as you want, and they are put in a horizontal row.

The program still only contains one call to pack because that call works its way down through the entire hierarchy of inner containers.

By the way, this program has ugly repetition in it.  Some people get round this by packing a lot of code into a single line:

      row.add(new JButton("One"));

A better way is to write your own layout methods, e.g.

      addButton(row, "One");

Back