Credits

Thursday, September 16, 2010

Box Layout of Java

When you need to pile components in rows or in columns, then a Box Layout can be used. To compare Grid Layout with Box Layout, Grid Layout makes your components in matrix or table format while Box Layout creates only a stack EITHER in a single row or single column.

The program below  illustrates the use of this layout along with Flow Layout.
[+/-] 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