Credits

Wednesday, September 15, 2010

Java's Flow Layout

One of the layout manager is Flow Layout which is the default layout for panels.  Flow Layout is used when you need to align evenly your components and line wrapping is employed to allow all components to be seen.

The constants that can be used with Flow Layout are the following:

FlowLayout.CENTER
FlowLayout.LEFT
FlowLayout.RIGHT

The program below illustrates the use of these constants.

[+/-] show/hide



import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class FlowLayoutDemo extends JFrame implements ActionListener{
JButton lb = new JButton("Left Button");
JButton rb = new JButton("Right Button");
FlowLayout layout = new FlowLayout();
Container con = getContentPane();
public FlowLayoutDemo()
{
con.setLayout(layout);
con.add(lb);
con.add(rb);

lb.addActionListener(this);
rb.addActionListener(this);


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if (source==lb)
layout.setAlignment(FlowLayout.LEFT);
else
layout.setAlignment(FlowLayout.RIGHT);
layout.layoutContainer(con);
}
public static void main (String [] args){
FlowLayoutDemo frm = new FlowLayoutDemo();
frm.setSize(300,100);
frm.setTitle("Flow Layout Demo");
frm.setVisible(true);
}
}

AddThis