Using multiple layout managers
Using multiple layout managers
As you can probably imagine, no one Layout manager is suitable for all the requirements of an application. They are normally used in cooperation with other Container controls. Thus a BorderLayout may be used for a Frame but a Panel will be added to the North. The panel is set to use a FlowLayout and buttons are added within the Panel. Another Panel might be added to the Centre which is set to the GridLayout and a series of Buttons added there.
The following code demonstrates the use of multiple layouts.
import javax.swing.*; import javax.swing.JPanel; import java.awt.*; /** * Demonstration of using multiple layouts * Marcus Green 2005 **/ public class MultiLay extends JFrame{ public static void main(String argv[]){ MultiLay ml=new MultiLay(); } MultiLay(){ /* Setup GridLayout with 2 rows and 1 column */ /** * This grid layout will set the button one to occupy all of * the top of the frame. The flow layout used in the second panel * means its preferred size will be respected and thus it will * occupy only enough space to show the text "two" * If you are using earlier than JDK 1.5 you will need * getContentPane code here **/ setLayout(new GridLayout(2,1)); add(new JButton("One")); JPanel jp = new JPanel(); jp.setLayout(new FlowLayout()); add(jp); jp.add(new Button("two")); setSize(400,300); setVisible(true); } }
MultiLay Screen shot
Last modified: Thursday, 24 July 2014, 2:54 PM