Credits

Sunday, February 27, 2011

Java's Flow Layout

Java's Flow Layout is the default layout of a panel. If you want components to be centered horizontally on your container, Flow Layout is the best choice. Further, with components automatically arranged across the containers,  we make sure that these components are given equal space.

We can further  change the alignment to LEFT, RIGHT, or CENTER.  The program below illustrates the use of Flow Layout.

[+/-] 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