Java Reference
In-Depth Information
Specifying a layout manager for a container is a simple operation. You just need to call the following
method:
public void setLayout(LayoutManager manager)
For example:
JPanel redPanel = new JPanel();
redPanel.setLayout(new BorderLayout());
The questions then are which layout managers exist and what does each of them do? The following
sections discuss each of the builtāin layout managers in detail and provide examples of all of them.
flowlayout
In a
FlowLayout
, all components will be arranged from left to right in the order that they are added.
When a row is filled, a new row is started. Resizing the container or changing the width of the
container programmatically thus changes the appearance. The
FlowLayout
is the default layout for
JPanel
.
Creating Flowing panels
try it out
In this Try It Out, you will create a
JFrame
, set its layout manager to use a
FlowLayout
, and add some
panels.
1.
As always, feel free to create a new project in Eclipse.
2.
Now make a rainbow. Create a class called
FlowLayoutFrame
with the following content:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FlowLayoutFrame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("FlowLayout frame");
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(makePanel(Color.red));
frame.getContentPane().add(makePanel(Color.orange));
frame.getContentPane().add(makePanel(Color.green));
frame.getContentPane().add(makePanel(Color.blue));
frame.getContentPane().add(makePanel(new Color(75, 0, 130)));
frame.getContentPane().add(makePanel(new Color(138, 43, 226)));
frame.pack();
Search WWH ::
Custom Search