Skip to main content

Java Layout Manager: ...

Java LayoutManagers

The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers. There are following classes that represents the layout managers:

  1. java.awt.BorderLayout
  2. java.awt.FlowLayout
  3. java.awt.GridLayout
  4. java.awt.CardLayout
  5. java.awt.GridBagLayout
  6. javax.swing.BoxLayout
  7. javax.swing.GroupLayout
  8. javax.swing.ScrollPaneLayout
  9. javax.swing.SpringLayout etc.

Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain one component only. It is the default layout of frame or window. The BorderLayout provides five constants for each region:

  1. public static final int NORTH
  2. public static final int SOUTH
  3. public static final int EAST
  4. public static final int WEST
  5. public static final int CENTER

Constructors of BorderLayout class:

  • BorderLayout(): creates a border layout but with no gaps between the components.
  • JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the components.

Java LayoutManagers

The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers. There are following classes that represents the layout managers:

  1. java.awt.BorderLayout
  2. java.awt.FlowLayout
  3. java.awt.GridLayout
  4. java.awt.CardLayout
  5. java.awt.GridBagLayout
  6. javax.swing.BoxLayout
  7. javax.swing.GroupLayout
  8. javax.swing.ScrollPaneLayout
  9. javax.swing.SpringLayout etc.

Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain one component only. It is the default layout of frame or window. The BorderLayout provides five constants for each region:

  1. public static final int NORTH
  2. public static final int SOUTH
  3. public static final int EAST
  4. public static final int WEST
  5. public static final int CENTER

Constructors of BorderLayout class:

  • BorderLayout(): creates a border layout but with no gaps between the components.
  • JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the components.

Java GridLayout

The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.

Constructors of GridLayout class

  1. GridLayout(): creates a grid layout with one column per component in a row.
  2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the components.
  3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps.

Example of GridLayout class

GridLayout class
  1. import java.awt.*;  
  2. import javax.swing.*;  
  3.   
  4. public class MyGridLayout{  
  5. JFrame f;  
  6. MyGridLayout(){  
  7.     f=new JFrame();  
  8.       
  9.     JButton b1=new JButton("1");  
  10.     JButton b2=new JButton("2");  
  11.     JButton b3=new JButton("3");  
  12.     JButton b4=new JButton("4");  
  13.     JButton b5=new JButton("5");  
  14.         JButton b6=new JButton("6");  
  15.         JButton b7=new JButton("7");  
  16.     JButton b8=new JButton("8");  
  17.         JButton b9=new JButton("9");  
  18.           
  19.     f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);  
  20.     f.add(b6);f.add(b7);f.add(b8);f.add(b9);  
  21.   
  22.     f.setLayout(new GridLayout(3,3));  
  23.     //setting grid layout of 3 rows and 3 columns  
  24.   
  25.     f.setSize(300,300);  
  26.     f.setVisible(true);  
  27. }  
  28. public static void main(String[] args) {  
  29.     new MyGridLayout();  
  30. }  
  31. }  

Java FlowLayout

The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel.

Fields of FlowLayout class

  1. public static final int LEFT
  2. public static final int RIGHT
  3. public static final int CENTER
  4. public static final int LEADING
  5. public static final int TRAILING

Constructors of FlowLayout class

  1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.
  2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap.
  3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given horizontal and vertical gap.

Example of FlowLayout class

FlowLayout class
  1. import java.awt.*;  
  2. import javax.swing.*;  
  3.   
  4. public class MyFlowLayout{  
  5. JFrame f;  
  6. MyFlowLayout(){  
  7.     f=new JFrame();  
  8.       
  9.     JButton b1=new JButton("1");  
  10.     JButton b2=new JButton("2");  
  11.     JButton b3=new JButton("3");  
  12.     JButton b4=new JButton("4");  
  13.     JButton b5=new JButton("5");  
  14.               
  15.     f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);  
  16.       
  17.     f.setLayout(new FlowLayout(FlowLayout.RIGHT));  
  18.     //setting flow layout of right alignment  
  19.   
  20.     f.setSize(300,300);  
  21.     f.setVisible(true);  
  22. }  
  23. public static void main(String[] args) {  
  24.     new MyFlowLayout();  
  25. }  
  26. }  

Java BoxLayout

The BoxLayout is used to arrange the components either vertically or horizontally. For this purpose, BoxLayout provides four constants. They are as follows:

Note: BoxLayout class is found in javax.swing package.

Fields of BoxLayout class

  1. public static final int X_AXIS
  2. public static final int Y_AXIS
  3. public static final int LINE_AXIS
  4. public static final int PAGE_AXIS

Constructor of BoxLayout class

  1. BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given axis.

Example of BoxLayout class with Y-AXIS:

BoxLayout class
  1. import java.awt.*;  
  2. import javax.swing.*;  
  3.   
  4. public class BoxLayoutExample1 extends Frame {  
  5.  Button buttons[];  
  6.   
  7.  public BoxLayoutExample1 () {  
  8.    buttons = new Button [5];  
  9.     
  10.    for (int i = 0;i<5;i++) {  
  11.       buttons[i] = new Button ("Button " + (i + 1));  
  12.       add (buttons[i]);  
  13.     }  
  14.   
  15. setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));  
  16. setSize(400,400);  
  17. setVisible(true);  
  18. }  
  19.   
  20. public static void main(String args[]){  
  21. BoxLayoutExample1 b=new BoxLayoutExample1();  
  22. }  
  23. }  

Example of BoxLayout class with X-AXIS

BoxLayout class example
  1. import java.awt.*;  
  2. import javax.swing.*;  
  3.   
  4. public class BoxLayoutExample2 extends Frame {  
  5.  Button buttons[];  
  6.   
  7.  public BoxLayoutExample2() {  
  8.    buttons = new Button [5];  
  9.     
  10.    for (int i = 0;i<5;i++) {  
  11.       buttons[i] = new Button ("Button " + (i + 1));  
  12.       add (buttons[i]);  
  13.     }  
  14.   
  15. setLayout (new BoxLayout(this, BoxLayout.X_AXIS));  
  16. setSize(400,400);  
  17. setVisible(true);  
  18. }  
  19.   
  20. public static void main(String args[]){  
  21. BoxLayoutExample2 b=new BoxLayoutExample2();  
  22. }  
  23. }  

Java CardLayout

The CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each component as a card that is why it is known as CardLayout.

Constructors of CardLayout class

  1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
  2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.

Commonly used methods of CardLayout class

  • public void next(Container parent): is used to flip to the next card of the given container.
  • public void previous(Container parent): is used to flip to the previous card of the given container.
  • public void first(Container parent): is used to flip to the first card of the given container.
  • public void last(Container parent): is used to flip to the last card of the given container.
  • public void show(Container parent, String name): is used to flip to the specified card with the given name.

Example of CardLayout class

CardLayout class
  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3.   
  4. import javax.swing.*;  
  5.   
  6. public class CardLayoutExample extends JFrame implements ActionListener{  
  7. CardLayout card;  
  8. JButton b1,b2,b3;  
  9. Container c;  
  10.     CardLayoutExample(){  
  11.           
  12.         c=getContentPane();  
  13.         card=new CardLayout(40,30);  
  14. //create CardLayout object with 40 hor space and 30 ver space  
  15.         c.setLayout(card);  
  16.           
  17.         b1=new JButton("Apple");  
  18.         b2=new JButton("Boy");  
  19.         b3=new JButton("Cat");  
  20.         b1.addActionListener(this);  
  21.         b2.addActionListener(this);  
  22.         b3.addActionListener(this);  
  23.               
  24.         c.add("a",b1);c.add("b",b2);c.add("c",b3);  
  25.                           
  26.     }  
  27.     public void actionPerformed(ActionEvent e) {  
  28.     card.next(c);  
  29.     }  
  30.   
  31.     public static void main(String[] args) {  
  32.         CardLayoutExample cl=new CardLayoutExample();  
  33.         cl.setSize(400,400);  
  34.         cl.setVisible(true);  
  35.         cl.setDefaultCloseOperation(EXIT_ON_CLOSE);  
  36.     }  
  37. }  

Java GridBagLayout

The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline.

The components may not be of same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells. Each component occupies one or more cells known as its display area. Each component associates an instance of GridBagConstraints. With the help of constraints object we arrange component's display area on the grid. The GridBagLayout manages each component's minimum and preferred sizes in order to determine component's size.

Fields

Modifier and TypeFieldDescription
double[]columnWeightsIt is used to hold the overrides to the column weights.
int[]columnWidthsIt is used to hold the overrides to the column minimum width.
protected Hashtable<Component,GridBagConstraints>comptableIt is used to maintains the association between a component and its gridbag constraints.
protected GridBagConstraintsdefaultConstraintsIt is used to hold a gridbag constraints instance containing the default values.
protected GridBagLayoutInfolayoutInfoIt is used to hold the layout information for the gridbag.
protected static intMAXGRIDSIZENo longer in use just for backward compatibility
protected static intMINSIZEIt is smallest grid that can be laid out by the grid bag layout.
protected static intPREFERREDSIZEIt is preferred grid size that can be laid out by the grid bag layout.
int[]rowHeightsIt is used to hold the overrides to the row minimum heights.
double[]rowWeightsIt is used to hold the overrides to the row weights.

Useful Methods

Modifier and TypeMethodDescription
voidaddLayoutComponent(Component comp, Object constraints)It adds specified component to the layout, using the specified constraints object.
voidaddLayoutComponent(String name, Component comp)It has no effect, since this layout manager does not use a per-component string.
protected voidadjustForGravity(GridBagConstraints constraints, Rectangle r)It adjusts the x, y, width, and height fields to the correct values depending on the constraint geometry and pads.
protected voidAdjustForGravity(GridBagConstraints constraints, Rectangle r)This method is for backwards compatibility only
protected voidarrangeGrid(Container parent)Lays out the grid.
protected voidArrangeGrid(Container parent)This method is obsolete and supplied for backwards compatibility
GridBagConstraintsgetConstraints(Component comp)It is for getting the constraints for the specified component.
floatgetLayoutAlignmentX(Container parent)It returns the alignment along the x axis.
floatgetLayoutAlignmentY(Container parent)It returns the alignment along the y axis.
int[][]getLayoutDimensions()It determines column widths and row heights for the layout grid.
protected GridBagLayoutInfogetLayoutInfo(Container parent, int sizeflag)This method is obsolete and supplied for backwards compatibility.
protected GridBagLayoutInfoGetLayoutInfo(Container parent, int sizeflag)This method is obsolete and supplied for backwards compatibility.
PointgetLayoutOrigin()It determines the origin of the layout area, in the graphics coordinate space of the target container.
double[][]getLayoutWeights()It determines the weights of the layout grid's columns and rows.
protected DimensiongetMinSize(Container parent, GridBagLayoutInfo info)It figures out the minimum size of the master based on the information from getLayoutInfo.
protected DimensionGetMinSize(Container parent, GridBagLayoutInfo info)This method is obsolete and supplied for backwards compatibility only

Example

  1. import java.awt.Button;  
  2. import java.awt.GridBagConstraints;  
  3. import java.awt.GridBagLayout;  
  4.   
  5. import javax.swing.*;  
  6. public class GridBagLayoutExample extends JFrame{  
  7.     public static void main(String[] args) {  
  8.             GridBagLayoutExample a = new GridBagLayoutExample();  
  9.         }  
  10.         public GridBagLayoutExample() {  
  11.     GridBagLayoutgrid = new GridBagLayout();  
  12.             GridBagConstraints gbc = new GridBagConstraints();  
  13.             setLayout(grid);  
  14.             setTitle("GridBag Layout Example");  
  15.             GridBagLayout layout = new GridBagLayout();  
  16.     this.setLayout(layout);  
  17.     gbc.fill = GridBagConstraints.HORIZONTAL;  
  18.     gbc.gridx = 0;  
  19.     gbc.gridy = 0;  
  20.     this.add(new Button("Button One"), gbc);  
  21.     gbc.gridx = 1;  
  22.     gbc.gridy = 0;  
  23.     this.add(new Button("Button two"), gbc);  
  24.     gbc.fill = GridBagConstraints.HORIZONTAL;  
  25.     gbc.ipady = 20;  
  26.     gbc.gridx = 0;  
  27.     gbc.gridy = 1;  
  28.     this.add(new Button("Button Three"), gbc);  
  29.     gbc.gridx = 1;  
  30.     gbc.gridy = 1;  
  31.     this.add(new Button("Button Four"), gbc);  
  32.     gbc.gridx = 0;  
  33.     gbc.gridy = 2;  
  34.     gbc.fill = GridBagConstraints.HORIZONTAL;  
  35.     gbc.gridwidth = 2;  
  36.     this.add(new Button("Button Five"), gbc);  
  37.             setSize(300300);  
  38.             setPreferredSize(getSize());  
  39.             setVisible(true);  
  40.             setDefaultCloseOperation(EXIT_ON_CLOSE);  
  41.       
  42.         }  
  43.       
  44. }  

Output:

Java Gridbaglayout 1

Example 2

  1. public class GridBagLayoutDemo {  
  2. final static boolean shouldFill = true;  
  3. final static boolean shouldWeightX = true;  
  4. final static boolean RIGHT_TO_LEFT = false;  
  5.   
  6. public static void addComponentsToPane(Container pane) {  
  7. if (RIGHT_TO_LEFT) {  
  8. pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);  
  9. }  
  10.   
  11. JButton button;  
  12. pane.setLayout(new GridBagLayout());  
  13. GridBagConstraints c = new GridBagConstraints();  
  14. if (shouldFill) {  
  15. //natural height, maximum width  
  16. c.fill = GridBagConstraints.HORIZONTAL;  
  17. }  
  18.   
  19. button = new JButton("Button 1");  
  20. if (shouldWeightX) {  
  21. c.weightx = 0.5;  
  22. }  
  23. c.fill = GridBagConstraints.HORIZONTAL;  
  24. c.gridx = 0;  
  25. c.gridy = 0;  
  26. pane.add(button, c);  
  27.   
  28. button = new JButton("Button 2");  
  29. c.fill = GridBagConstraints.HORIZONTAL;  
  30. c.weightx = 0.5;  
  31. c.gridx = 1;  
  32. c.gridy = 0;  
  33. pane.add(button, c);  
  34.   
  35. button = new JButton("Button 3");  
  36. c.fill = GridBagConstraints.HORIZONTAL;  
  37. c.weightx = 0.5;  
  38. c.gridx = 2;  
  39. c.gridy = 0;  
  40. pane.add(button, c);  
  41.   
  42. button = new JButton("Long-Named Button 4");  
  43. c.fill = GridBagConstraints.HORIZONTAL;  
  44. c.ipady = 40;      //make this component tall  
  45. c.weightx = 0.0;  
  46. c.gridwidth = 3;  
  47. c.gridx = 0;  
  48. c.gridy = 1;  
  49. pane.add(button, c);  
  50.   
  51. button = new JButton("5");  
  52. c.fill = GridBagConstraints.HORIZONTAL;  
  53. c.ipady = 0;       //reset to default  
  54. c.weighty = 1.0;   //request any extra vertical space  
  55. c.anchor = GridBagConstraints.PAGE_END; //bottom of space  
  56. c.insets = new Insets(10,0,0,0);  //top padding  
  57. c.gridx = 1;       //aligned with button 2  
  58. c.gridwidth = 2;   //2 columns wide  
  59. c.gridy = 2;       //third row  
  60. pane.add(button, c);  
  61. }  
  62.   
  63.   
  64. private static void createAndShowGUI() {  
  65. //Create and set up the window.  
  66. JFrame frame = new JFrame("GridBagLayoutDemo");  
  67. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  68.   
  69. //Set up the content pane.  
  70. addComponentsToPane(frame.getContentPane());  
  71.   
  72. //Display the window.  
  73. frame.pack();  
  74. frame.setVisible(true);  
  75. }  
  76.   
  77. public static void main(String[] args) {  
  78. javax.swing.SwingUtilities.invokeLater(new Runnable() {  
  79. public void run() {  
  80. createAndShowGUI();  
  81. }  
  82. });  
  83. }  
  84. }  

Output:

Java Gridbaglayout 2


GroupLayout

GroupLayout groups its components and places them in a Container hierarchically. The grouping is done by instances of the Group class.

Group is an abstract class and two concrete classes which implement this Group class are SequentialGroup and ParallelGroup.

SequentialGroup positions its child sequentially one after another where as ParallelGroup aligns its child on top of each other.

The GroupLayout class provides methods such as createParallelGroup() and createSequentialGroup() to create groups.

GroupLayout treats each axis independently. That is, there is a group representing the horizontal axis, and a group representing the vertical axis. Each component must exists in both a horizontal and vertical group, otherwise an IllegalStateException is thrown during layout, or when the minimum, preferred or maximum size is requested.

Nested Classes

Modifier and TypeClassDescription
static classGroupLayout.AlignmentEnumeration of the possible ways ParallelGroup can align its children.
classGroupLayout.GroupGroup provides the basis for the two types of operations supported by GroupLayout: laying out components one after another (SequentialGroup) or aligned (ParallelGroup).
classGroupLayout.ParallelGroupIt is a Group that aligns and sizes it's children.
classGroupLayout.SequentialGroupIt is a Group that positions and sizes its elements sequentially, one after another.

Fields

Modifier and TypeFieldDescription
static intDEFAULT_SIZEIt indicates the size from the component or gap should be used for a particular range value.
static intPREFERRED_SIZEIt indicates the preferred size from the component or gap should be used for a particular range value.

Constructors

GroupLayout(Container host)It creates a GroupLayout for the specified Container.

Useful Methods

Modifier and TypeFieldDescription
voidaddLayoutComponent(Component component, Object constraints)It notify that a Component has been added to the parent container.
voidaddLayoutComponent(String name, Component component)It notify that a Component has been added to the parent container.
GroupLayout.ParallelGroupcreateBaselineGroup(boolean resizable, boolean anchorBaselineToTop)It creates and returns a ParallelGroup that aligns it's elements along the baseline.
GroupLayout.ParallelGroupcreateParallelGroup()It creates and returns a ParallelGroup with an alignment of Alignment.LEADING
GroupLayout.ParallelGroupcreateParallelGroup(GroupLayout.Alignment alignment)It creates and returns a ParallelGroup with the specified alignment.
GroupLayout.ParallelGroupcreateParallelGroup(GroupLayout.Alignment alignment, boolean resizable)It creates and returns a ParallelGroup with the specified alignment and resize behavior.
GroupLayout.SequentialGroupcreateSequentialGroup()It creates and returns a SequentialGroup.
booleangetAutoCreateContainerGaps()It returns true if gaps between the container and components that border the container are automatically created.
booleangetAutoCreateGaps()It returns true if gaps between components are automatically created.
booleangetHonorsVisibility()It returns whether component visiblity is considered when sizing and positioning components.
floatgetLayoutAlignmentX(Container parent)It returns the alignment along the x axis.
floatgetLayoutAlignmentY(Container parent)It returns the alignment along the y axis.
DimensionmaximumLayoutSize(Container parent)It returns the maximum size for the specified container.

Example

  1. public class GroupExample {  
  2.     public static void main(String[] args) {  
  3.         JFrame frame = new JFrame("GroupLayoutExample");  
  4.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  5.         Container contentPanel = frame.getContentPane();  
  6.         GroupLayout groupLayout = new GroupLayout(contentPanel);  
  7.   
  8.         contentPanel.setLayout(groupLayout);  
  9.   
  10.         JLabel clickMe = new JLabel("Click Here");  
  11.         JButton button = new JButton("This Button");  
  12.   
  13.         groupLayout.setHorizontalGroup(  
  14.                     groupLayout.createSequentialGroup()  
  15.                                 .addComponent(clickMe)  
  16.                                 .addGap(1020100)  
  17.                                 .addComponent(button));  
  18.         groupLayout.setVerticalGroup(  
  19.                      groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)  
  20.                                 .addComponent(clickMe)  
  21.                                 .addComponent(button));  
  22.         frame.pack();  
  23.         frame.setVisible(true);  
  24.     }  
  25. }  

Output:

Java Grouplayout 1

Example 2

  1. import java.awt.Container;  
  2. import javax.swing.GroupLayout;  
  3. import javax.swing.JButton;  
  4. import javax.swing.JFrame;  
  5. import static javax.swing.GroupLayout.Alignment.*;  
  6. public class GroupExample2 {  
  7.     public static void main(String[] args) {  
  8.         JFrame frame = new JFrame("GroupLayoutExample");  
  9.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  10.         Container myPanel = frame.getContentPane();  
  11.   
  12.         GroupLayout groupLayout = new GroupLayout(myPanel);  
  13.         groupLayout.setAutoCreateGaps(true);  
  14.         groupLayout.setAutoCreateContainerGaps(true);  
  15.         myPanel.setLayout(groupLayout);  
  16.   
  17.         JButton b1 = new JButton("Button One");  
  18.         JButton b2 = new JButton("Button Two");  
  19.         JButton b3 = new JButton("Button Three");  
  20.   
  21.         groupLayout.setHorizontalGroup(groupLayout.createSequentialGroup()  
  22.                 .addGroup(groupLayout.createParallelGroup(LEADING).addComponent(b1).addComponent(b3))  
  23.                 .addGroup(groupLayout.createParallelGroup(TRAILING).addComponent(b2)));  
  24.   
  25.         groupLayout.setVerticalGroup(groupLayout.createSequentialGroup()  
  26.                 .addGroup(groupLayout.createParallelGroup(BASELINE).addComponent(b1).addComponent(b2))  
  27.                 .addGroup(groupLayout.createParallelGroup(BASELINE).addComponent(b3)));  
  28.   
  29.         frame.pack();  
  30.         frame.setVisible(true);  
  31.     }  
  32. }  

Output:

Java Grouplayout 2


Java SpringLayout

SpringLayout arranges the children of its associated container according to a set of constraints.Constraints are nothing but horizontal and vertical distance between two component edges. Every constrains are represented by a SpringLayout.Constraint object.

Each child of a SpringLayout container, as well as the container itself, has exactly one set of constraints associated with them.

Each edge position is dependent on the position of the other edge. If a constraint is added to create new edge than the previous binding is discarded. SpringLayout doesn't automatically set the location of the components it manages.

Nested Classes

Modifier and TypeClassDescription
static classSpringLayout.ConstraintsIt is a Constraints object helps to govern component's size and position change in a container that is controlled by SpringLayout

Fields

Modifier and TypeFieldDescription
static StringBASELINEIt specifies the baseline of a component.
static StringEASTIt specifies the right edge of a component's bounding rectangle.
static StringHEIGHTIt specifies the height of a component's bounding rectangle.
static StringHORIZONTAL_CENTERIt specifies the horizontal center of a component's bounding rectangle.
static StringNORTHIt specifies the top edge of a component's bounding rectangle.
static StringSOUTHIt specifies the bottom edge of a component's bounding rectangle.
static StringVERTICAL_CENTERIt specifies the vertical center of a component's bounding rectangle.
static StringWESTIt specifies the left edge of a component's bounding rectangle.
static StringWIDTHIt specifies the width of a component's bounding rectangle.

Useful Methods

Modifier and TypeMethodDescription
voidaddLayoutComponent(Component component, Object constraints)If constraints is an instance of SpringLayout. Constraints, associates the constraints with the specified component.
voidaddLayoutComponent(String name, Component c)Has no effect, since this layout manager does not use a per-component string.
SpringgetConstraint(String edgeName, Component c)It returns the spring controlling the distance between the specified edge of the component and the top or left edge of its parent.
SpringLayout.ConstraintsgetConstraints(Component c)It returns the constraints for the specified component.
floatgetLayoutAlignmentX(Container p)It returns 0.5f (centered).
floatgetLayoutAlignmentY(Container p)It returns 0.5f (centered).
voidinvalidateLayout(Container p)It Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
voidlayoutContainer(Container parent)It lays out the specified container.
DimensionmaximumLayoutSize(Container parent)It is used to calculates the maximum size dimensions for the specified container, given the components it contains.
DimensionminimumLayoutSize(Container parent)It is used to calculates the minimum size dimensions for the specified container, given the components it contains.
DimensionpreferredLayoutSize(Container parent)It is used to calculates the preferred size dimensions for the specified container, given the components it contains.

Example

  1. import java.awt.Container;  
  2. import javax.swing.JFrame;  
  3. import javax.swing.JLabel;  
  4. import javax.swing.JTextField;  
  5. import javax.swing.SpringLayout;  
  6. public class MySpringDemo {  
  7.      private static void createAndShowGUI() {  
  8.             JFrame frame = new JFrame("MySpringDemp");  
  9.             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  10.   
  11.             Container contentPane = frame.getContentPane();  
  12.             SpringLayout layout = new SpringLayout();  
  13.             contentPane.setLayout(layout);  
  14.   
  15.             JLabel label = new JLabel("Label: ");  
  16.             JTextField textField = new JTextField("My Text Field"15);  
  17.             contentPane.add(label);  
  18.             contentPane.add(textField);  
  19.        
  20.             layout.putConstraint(SpringLayout.WEST, label,6,SpringLayout.WEST, contentPane);  
  21.             layout.putConstraint(SpringLayout.NORTH, label,6,SpringLayout.NORTH, contentPane);  
  22.             layout.putConstraint(SpringLayout.WEST, textField,6,SpringLayout.EAST, label);  
  23.             layout.putConstraint(SpringLayout.NORTH, textField,6,SpringLayout.NORTH, contentPane);  
  24.             layout.putConstraint(SpringLayout.EAST, contentPane,6,SpringLayout.EAST, textField);  
  25.             layout.putConstraint(SpringLayout.SOUTH, contentPane,6,SpringLayout.SOUTH, textField);  
  26.   
  27.             frame.pack();  
  28.             frame.setVisible(true);  
  29.         }  
  30.         public static void main(String[] args) {  
  31.             javax.swing.SwingUtilities.invokeLater(new Runnable() {  
  32.                 public void run() {  
  33.                     createAndShowGUI();  
  34.                 }  
  35.             });  
  36.         }  
  37.     }  

Output:

Java Springlayout 1

ScrollPaneLayout

The layout manager used by JScrollPane. JScrollPaneLayout is responsible for nine components: a viewport, two scrollbars, a row header, a column header, and four "corner" components.

Nested Class

Modifier and TypeClassDescription
static classScrollPaneLayout.UIResourceIt is UI resource version of ScrollPaneLayout.

Field

Modifier and TypeFieldDescription
protected JViewportcolHeadIt is column header child.
protected JScrollBarhsbIt is scrollpane's horizontal scrollbar child.
protected inthsbPolicyIt displays policy for the horizontal scrollbar.
protected ComponentlowerLeftThis displays the lower left corner.
protected ComponentlowerRightThis displays in the lower right corner.
protected JViewportrowHeadIt is row header child.
protected ComponentupperLeftThis component displays in the upper left corner.
protected ComponentupperRightThis component displays in the upper right corner.
protected JViewportviewportIt is scrollpane's viewport child.
protected JScrollBarvsbIt is scrollpane's vertical scrollbar child.
protected intvsbPolicyIt is the display policy for the vertical scrollbar.

Useful methods

Modifier and TypeMethodDescription
voidaddLayoutComponent(String s, Component c)It adds the specified component to the layout.
protected ComponentaddSingletonComponent(Component oldC, Component newC)It removes an existing component.
JViewportgetColumnHeader()It returns the JViewport object that is the column header.
ComponentgetCorner(String key)It returns the Component at the specified corner.
JScrollBargetHorizontalScrollBar()It returns the JScrollBar object that handles horizontal scrolling.
intgetHorizontalScrollBarPolicy()It returns the horizontal scrollbar-display policy.
JViewportgetRowHeader()It returns the JViewport object that is the row header.
JScrollBargetVerticalScrollBar()It returns the JScrollBar object that handles vertical scrolling.
intgetVerticalScrollBarPolicy()It returns the vertical scrollbar-display policy.
JViewportgetViewport()It returns the JViewport object that displays the scrollable contents.

Example:

  1. import javax.swing.ImageIcon;  
  2. import javax.swing.JFrame;  
  3. import javax.swing.JLabel;  
  4. import javax.swing.JScrollPane;  
  5. public class ScrollPaneDemo extends JFrame  
  6. {  
  7. public ScrollPaneDemo() {  
  8. super("ScrollPane Demo");  
  9. ImageIcon img = new ImageIcon("child.png");  
  10.   
  11. JScrollPane png = new JScrollPane(new JLabel(img));  
  12.   
  13. getContentPane().add(png);  
  14. setSize(300,250);  
  15. setVisible(true);  
  16. }  
  17.   
  18. public static void main(String[] args) {  
  19. new ScrollPaneDemo();  
  20. }  
  21. }  

Output:

Java Scrollpanellayout 1





Anurag Rana Educator CSE/IT

Comments

Popular posts from this blog

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);               f.setSize( 400 , 400 );               f.setLayout( null );               f.setVisible( true );   }   public   static   void  main(String args[]){           new  ScrollbarExample();   }   }   Output: Java AWT Scrollbar Example with AdjustmentListener import  java.awt.*;   import  java.awt.event.*;   class  ScrollbarExample{        ScrollbarExample(){               Frame f=  new  Frame( "Scro

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari

C++ this Pointer, static, struct and Enumeration

C++ this Pointer In C++ programming,  this  is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++. It can be used  to pass current object as a parameter to another method. It can be used  to refer current class instance variable. It can be used  to declare indexers. C++ this Pointer Example Let's see the example of this keyword in C++ that refers to the fields of current class. #include <iostream>    using   namespace  std;   class  Employee {       public :           int  id;  //data member (also instance variable)               string name;  //data member(also instance variable)            float  salary;          Employee( int  id, string name,  float  salary)             {                   this ->id = id;                  this ->name = name;                  this ->salary = salary;            }             void  display()             {                 cout<<id<< "  " <<name<&