Skip to content
June 18, 2009 / Narayan

Trick of Positioning the Containers of JFrame

Many developers want their own Layout Manager with user-defined so JAVA has provided a separate method for the every container of JFrame Component and that method is setBounds(). This method helps the developers to position the container as per their need .

About SetBounds() method:

This method consists four parameter

  Syntax:
     xxx.setBounds(int x_axis, int y_axis, int width, int height);

We can arrange the containers with the help of this method easily.

A example of this method is shown below:

import javax.swing.*;

public class LoginPanel {

public LoginPanel() {

}

public static void main (String[] args) {
JFrame frame = new JFrame();

frame.setLayout(null);

//For Positioning the Containers

//Labeling
JLabel label = new JLabel("WELCOME TO"+
"LOGIN PANEL", JLabel.CENTER);
JLabel user = new JLabel("UserName:\t");
JLabel pass = new JLabel("Password:\t");

//Some features of SETBOUNDS() Methods
//setBounds(x-axis, y-axis, width, height);
label.setBounds(150,10,220,20);
user.setBounds(150,50,100,50);
pass.setBounds(150,90,100,50);

//TextField
JTextField userField = new JTextField();
JPasswordField passField = new JPasswordField();

//Some of the features of SETBOUNDS() Methods
//setBounds(x-axis, y-axis, width, height);
userField.setBounds(250,65,80,20);
passField.setBounds(250,105,80,20);

//Button
JButton but1 = new JButton("Submit");

//setBounds(x-axis, y-axis, width, height);
but1.setBounds(200,150,100,20);

//adding containers to JFRAME
frame.getContentPane().add(label);
frame.getContentPane().add(user);
frame.getContentPane().add(userField);
frame.getContentPane().add(pass);
frame.getContentPane().add(passField);
frame.getContentPane().add(but1);

//features of JFrame
//Although these can be defined
//before the containers.
//We defined at last
frame.setVisible(true);
frame.setSize(500,300);

}

}

And the output must be like this:

Login Panel Output

Login Panel Output

Advertisements

2 Comments

Leave a Comment
  1. anurag / Jul 28 2009 2:36 am

    Good Example

    • Narayan / Jul 29 2009 1:31 am

      Oh ! Thanks ‘anurag’

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: