Saturday, February 28, 2009

Null Layout or Absolute Positioning in JAVA

Hi freinds,

Most of the time every developer is thinking which layout is to be set.
So that all the added component (like button,Text box etc.) can not
affect while resizing the JFrame or their container.

So we that there are number of layout to do so.
And for many of the users GridBagLayout is best for their work.

But many of the user also feel that it is some difficult and takes too
much lines to code.

So my dear friend use NullLayout which kept is sort and sweet.
On this layout you can easily choose X, Y postion and also width and
height of your particular component.

See the snapshot you can also put button overlapping.
Same as other component.

It is not a Layout Manager and not need to add like others.
just setLayout(null); will add this to your component.

I am created a very simple application which implement this method.
just go through it.

For source code see below


/*
* Program for setting null layout or absolute positioning
* you can put button over another button
* Copyright 2009 @ yuvadeveloper
* Code By:- Prashant Chandrakar
*
*/

import java.awt.*;

import javax.swing.*;

import javax.swing.plaf.synth.*;


public class NullLayout extends JFrame

{
NullLayout()
{

super("Null Layout Prashant Chandrakar");

try

{

JFrame.setDefaultLookAndFeelDecorated(true);

this.getContentPane().setBackground(Color.GRAY);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


JLabel uname = new JLabel("UserName");

JLabel pword = new JLabel("Password");

JTextField utxt = new JTextField(20);

JTextField ptxt = new JTextField(20);

this.setLayout(null);

////by using this method set the x,y ,width ,height
uname.setBounds(40, 27, 100, 25);
utxt.setBounds(150, 27, 100, 25);
pword.setBounds(40, 70, 100, 25);
ptxt.setBounds(150, 70, 100, 25);

this.add(uname);

this.add(utxt);

this.add(pword);

this.add(ptxt);

JButton btsave = new JButton("SAVE");

JButton btcancel = new JButton("CANCEL");

btcancel.setBounds(120, 127, 104, 25);
btsave.setBounds(100, 107, 104, 25);

this.add(btsave);

this.add(btcancel);

}

catch (Exception e)

{

System.out.println(e);

}

this.setSize(350, 200);

this.setVisible(true);

}

public static void main(String[] args) throws Throwable

{

new NullLayout();

}
}

Snapshot:-













No comments:

Post a Comment