Java No Layout Manager setBounds()


Java No Layout Manager setBounds()

Dimension class

Another example on Java No Layout Manager setBounds()

java.awt.Dimension class two fields height and width that give the height and width of a component. Following program uses setSize() and getSize() methods of Component class to set the size to a component and get the size of the component.

import java.awt.*;
import java.awt.event.*; 
public class TwoSizes extends Frame
{   
  public TwoSizes()   
  {  
    setLayout( null ) ;
    Button btn1 = new Button("OK" );		
    btn1.setBounds(30, 60, 100, 40);    

    Button btn2 = new Button("Cancel");		

    Dimension d1 = btn1.getSize();
    Dimension d2 = new Dimension(d1.width*2, d1.height*2);
    btn2.setBounds(150, 60, 100, 40);
    btn2.setSize(d2);

    add(btn1);    add(btn2);

    setSize(600, 300);  
    setVisible( true ) ;
  } 
  public static void main( String args[])   
  {
    new TwoSizes();
  } 
}

Java No Layout Manager setBounds()

btn1.setBounds(30, 60, 100, 40);

The button btn1 is set to a size of 100 width, 40 height and placed at pixels 30 and 60.

Dimension d1 = btn1.getSize();
Dimension d2 = new Dimension(d1.width*2, d1.height*2);

The getSize() method of Button (inherited from Component class) returns the size of the button btn1 as a Dimension object. Another Dimension object d2 is created with double the size of width and height of btn1. width and height are the fields (variables) of Dimension class that return the width and height of the component wrapped with it.

btn2.setBounds(150, 60, 100, 40);
btn2.setSize(d2);

Initially, a location and size is given to the button btn2. Later the size is changed to the double size of btn1 and placed at x and y coordinates 150 and 60.

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.