01 October 2010

Null Layout Manager (swing)

Layout Managers are used in the orginization of Panels and Frames. The proper layout should be chosen to accomodate, frame resizings and use.


Null:
*No Layout, items must be manually positioned and arranged.
This layout should only be used if the window will not and cannot be resized, as the item in the window will stay where they are placed, be that hidden or clumped in one corner of a window.

CODE example:
import java.awt.event.*;
import javax.swing.*;

public class NullLayoutExample extends JFrame {

       public NoLayoutExample(String name) {
              super(name);
              JTextField newItemField;
              JList itemsList;
              JButton addButton;
              JButton removeButton;

              getContentPane().setLayout(null);

              //The text field
              newItemField = new JTextField();
              newItemField.setLocation(12,12);
              newItemField.setSize(150,30);
              getContentPane().add(newItemField);

              //The Add button
              addButton = new JButton(“Add”);
              addButton.setMnemonic(‘A’);
              addButton.setLocation(174, 12);
              addButton.setSize(100,30);
              getContentPane().add(addButton);

              //The List
              itemsList = new JList();
              JScrollPane scrollPane = new JScrollPane(itemsList,
              ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
              ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              scrollPane.setLocation(12,45);
              scrollPane.setSize(150,150);
              getContentPane().add(scrollPane);

              //The Remove button
              removeButton = new JButton(“Remove”);
              removeButton.setMnemonic(‘R’);
              removeButton.setLocation(174,45);
              removeButton.setSize(100,30);
              getContentPane().add(removeButton);
       }

       public static void main(String[] args) {
              JFrame frame = new NoLayoutExample(“NULL Example”);
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.setSize(286, 230);
              frame.setResizable(false);
              frame.setVisible(true);
       }
}

No comments:

Post a Comment