Java No Layout Manager setBounds()

We know earlier in "Java Layout Managers" that two styles of placing components in containers – pixel format and position format. Now let us discuss clearly what pixel format is and how to place a component in terms of pixels.

We also know earlier, the default layout manager for Frame is BorderLayout and for Panel and Applet, it is FlowLayout. To use pixel format, first we must set the default layout manager of the container to null. To give the size and location, setBounds() method is used. But, this style is very rarely used (to avoid the complexity of GridBagLayout).

Following is the method signature as defined in java.awt.Component class.

setBounds(int x, int y, int width, int height): First two coordinates x and y give the position in the container and the last two width and height give the size of the component.

Example on Java No Layout Manager setBounds()

In the following program, one label and two buttons are placed using setBounds() method.

import java.awt.*;
public class NullLayoutManager extends Frame
{
  Button agreedBut, denyBut;
  Label sign;
  public NullLayoutManager()
  {
    super("No Layout Manager");
    setLayout(null);

    sign = new Label("Click Your Acceptance");
    agreedBut = new Button("AGREED");
    denyBut = new Button("DENIED");
 
    sign.setBounds(80, 35, 130, 25);
    agreedBut.setBounds(60, 75, 75, 25);
    denyBut.setBounds(150, 75, 75, 25);
    
    add(sign);   add(agreedBut);  add(denyBut);

    setSize(260, 130);
    setVisible(true);
  }
  public static void main(String args[])
  {
    new NullLayoutManager ();
  }
}

Java No Layout Manager setBounds()

super(“No Layout Manager”);

This is another style of using setTitle(). The super class constructor of Frame is called, with super(), and passed the string as parameter and this string is placed on the frame title bar.

setLayout(null);

To use setBounds() method, first the default layout manager BorderLayout of frame should be set to null.

sign.setBounds(80, 35, 130, 25);
agreedBut.setBounds(60, 75, 75, 25);

The label sign is placed at x-coordinate of 80 and y-coodinate 35 pixels. The width of the label is given as 130 pixels and height as 25 pixels. Simialrly, the agreeBut is placed at 60 and 75 coordinates with 75 pixels width and 25 height.

7 thoughts on “Java No Layout Manager setBounds()”

  1. I want to know that can set size any cells of container with GridBagLayout manager???
    thank you for your website!

Leave a Comment

Your email address will not be published.