Credits

Sunday, February 27, 2011

Java's Box Layout

Another interesting Layout Manager is the Box Layout that allows components to be aligned vertically or horizontally. Unlike Grid Layout where components are aligned in tabular format, Box Layout provides one row or column for components.

Using the parameters below gives us a container where components are stacked vertically:

BoxLayout horizontal =new BoxLayout(commandPane,BoxLayout.Y_AXIS);

See the program for complete illustration.
[+/-] show/hide


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

public class BoxLayoutDemo extends JFrame {

public BoxLayoutDemo()
{


super("Stacker");
setSize(430,150);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create top panel
JPanel commandPane=new JPanel();
BoxLayout horizontal =new BoxLayout(commandPane,BoxLayout.Y_AXIS);
commandPane.setLayout(horizontal);
JButton subscribe = new JButton("Subscribe");
JButton unsubscribe = new JButton("Unsubscribe");
JButton refresh = new JButton("Refresh");
JButton save = new JButton("Save");

commandPane.add(subscribe);
commandPane.add(unsubscribe);
commandPane.add(refresh);
commandPane.add(save);

//create bottom panel
JPanel textPane=new JPanel();
JTextArea txt = new JTextArea(4,70);
JScrollPane scrollPane=new JScrollPane(txt);

//put them together
FlowLayout flow =new FlowLayout();
setLayout(flow);
add(commandPane);
add(scrollPane);
setVisible(true);



}

public static void main (String [] args){
BoxLayoutDemo frm = new BoxLayoutDemo();

}
}

AddThis