Layout
Home ] Up ] Adding Buttons ] [ Layout ]

 

 

What's happening here?  

We're using something called a layout manager.  In this case, we're using a particular layout manager -- FlowLayout.   But how did we end up using it?

It turns out that FlowLayout is the default layout manager for a JPanel, so we get it for free in our examples above.

We can be explicit about using the FlowLayout manager.  We can also change its default behavior.  For example, we can specify that it left-align, instead of centering, and specify the gap between the components, in both the horizontal and vertical direction:

package swingExamples;

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

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

class FlowButtons3Panel extends JPanel
{
  public FlowButtons3Panel()
  {
    setBackground(Color.lightGray);
    setLayout(
        new FlowLayout(FlowLayout.LEFT, // Alignment 
                       20, // Horizontal gap
                       0   // Vertical gap
                      )
             );
    add(m_yellow);
    add(m_blue);
    add(m_red);
    add(m_orange);
    add(m_cyan);
    add(m_pink);
    add(m_white);
  }

  ////////////// Data //////////////////
  private JButton m_yellow = new JButton("Yellow");
  private JButton m_blue = new JButton("Blue");
  private JButton m_red = new JButton("Red");
  private JButton m_orange = new JButton("Orange");
  private JButton m_cyan = new JButton("Cyan");
  private JButton m_pink = new JButton("Pink");
  private JButton m_white = new JButton("White");
}

class FlowButtons3Frame extends JFrame
{
  public FlowButtons3Frame()
  {
    setTitle("FlowButtons");
    setSize(300, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container contentPane = getContentPane();
    contentPane.add( new FlowButtons3Panel() );
  }
}

public class FlowButtons3
{
  public static void main(String[] args)
  {
    FlowButtons3Frame frame = new FlowButtons3Frame();
    frame.setVisible(true);
  }
}

which produces the following results:

 

This page was last modified on 02 October, 2007