Learning Java
Custom Search

Previous Next

Absolute Positioning

It is not recommended, but it's possible to avoid the use of a layout manager by setting it to null. Then you can specify the exact positions and sizes in pixels of the components on the screen, except for a MenuBar.

After you have compiled and tested the code below, try resizing the window. Notice that the components on the frame do not adjust their sizes and positions based on the size of the window.

In the code below, notice that the layout manager is removed with

    pane.setLayout(null);

Also, note the exact location is specified for each of the buttons using

    Rectangle(xposition, yposition, width, height).

For example, the dog button is placed at the (x,y) coordinates of (80,90) and it is 100 pixels wide and 50 pixels high.

    dog.setBounds(new Rectangle(80, 90, 100, 50));
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class AbsPos extends JFrame {
    JButton dog = new JButton("Dog");
    JButton cat = new JButton("Cat");
    JButton bird = new JButton("Bird");
    JButton mouse = new JButton("Mouse");

    public AbsPos() {
        super("Abosolute Positioning Layout Test");
        setSize(260, 260);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel pane = new JPanel();
        pane.setLayout(null);
	dog.setBounds(new Rectangle(80, 90, 100, 50));
	cat.setBounds(new Rectangle(80, 190, 60, 30));
	bird.setBounds(new Rectangle(30, 50, 80, 20));
	mouse.setBounds(new Rectangle(100, 20, 150, 30));
        pane.add(dog);
        pane.add(cat);
        pane.add(bird);
        pane.add(mouse);

        add(pane);
        setVisible(true);
    }

    public static void main(String[] arguments) {
        AbsPos frame = new AbsPos();
    }
}

 

Previous Next

Steps In Learning

Contact us

Copyright © 2008      N. Nelson      All Rights Reserved