Kinesia Online Course
Object Oriented Programming
Kinesia LLC, 2003
    1. A Little Taste of Java
    2. Abstraction and Modeling
    3. Objects and Classes
    4. Object Interactions
    5. UML and Relationships between Objects
    6. Collection of Objects
    7. Some Final Concepts
    8. Object Modeling and Use Cases
    9. Modeling of Dynamic Behavaior and Sequence Diagrams
    10. A Deeper Look at Java
    11. Java Layout
    12. Java Events
    
    
    
    Java Layout
    1. GUI Design

    2. know the user
    3. prevent user errors
    4. optimize user abilities
    5. be consistent
    6. Layout Managers

    7. A layout manager is an object that governs how components are arranged in a container.

    8. Every container has a default layout manager.

    9. A container's layout manager is consulted whenever a change to the visual appearance of its contents might be needed.

    10. Each time a component is added, the layout manager readjusts the existing components
    11. Several AWT and Swing classes provide layout managers for general use:

      //********************************************************************
      //  LayoutDemo.java       Authors: Lewis/Loftus
      //
      //  Demonstrates the use of flow, border, grid, and box layouts.
      //********************************************************************
      
      import javax.swing.*;
      
      public class LayoutDemo
      {
         //-----------------------------------------------------------------
         //  Sets up a frame containing a tabbed pane. The panel on each
         //  tab demonstrates a different layout manager.
         //-----------------------------------------------------------------
         public static void main (String[] args)
         {
            JFrame frame = new JFrame ("Layout Manager Demo");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      
            JTabbedPane tp = new JTabbedPane();
            tp.addTab ("Intro", new IntroPanel());
            tp.addTab ("Flow", new FlowPanel());
            tp.addTab ("Border", new BorderPanel());
            tp.addTab ("Grid", new GridPanel());
            tp.addTab ("Box", new BoxPanel());
      
            frame.getContentPane().add(tp);
            frame.pack();
            frame.setVisible(true);
         }
      }
      
      //********************************************************************
      //  IntroPanel.java       Authors: Lewis/Loftus
      //
      //  Represents the introduction panel for the LayoutDemo program.
      //********************************************************************
      
      import java.awt.*;
      import javax.swing.*;
      
      public class IntroPanel extends JPanel
      {
         //-----------------------------------------------------------------
         //  Sets up this panel with two labels.
         //-----------------------------------------------------------------
         public IntroPanel()
         {
            setBackground (Color.green);
      
            JLabel l1 = new JLabel ("Layout Manager Demonstration");
            JLabel l2 = new JLabel ("Choose a tab to see an example of " +
                                    "a layout manager.");
      
            add (l1);
            add (l2);
         }
      }
        

      BorderLayout

      A picture of a GUI that uses BorderLayout

      Every content pane is initialized to use a BorderLayout. A BorderLayout places components in up to five areas: top, bottom, left, right, and center. All extra space is placed in the center area.

      //********************************************************************
      //  BorderPanel.java       Authors: Lewis/Loftus
      //
      //  Represents the panel in the LayoutDemo program that demonstrates
      //  the border layout manager.
      //********************************************************************
      
      import java.awt.*;
      import javax.swing.*;
      
      public class BorderPanel extends JPanel
      {
         //-----------------------------------------------------------------
         //  Sets up this panel with a button in each area of a border
         //  layout to show how it affects their position, shape, and size.
         //-----------------------------------------------------------------
         public BorderPanel()
         {
            setLayout (new BorderLayout());
      
            setBackground (Color.green);
      
            JButton b1 = new JButton ("BUTTON 1");
            JButton b2 = new JButton ("BUTTON 2");
            JButton b3 = new JButton ("BUTTON 3");
            JButton b4 = new JButton ("BUTTON 4");
            JButton b5 = new JButton ("BUTTON 5");
      
            add (b1, BorderLayout.CENTER);
            add (b2, BorderLayout.NORTH);
            add (b3, BorderLayout.SOUTH);
            add (b4, BorderLayout.EAST);
            add (b5, BorderLayout.WEST);
         }
      }
        

      BoxLayout

      A picture of a GUI that uses BoxLayout

      The BoxLayout class puts components in a single row or column. It respects the components' requested maximum sizes and also lets you align components.

      //********************************************************************
      //  BoxPanel.java       Authors: Lewis/Loftus
      //
      //  Represents the panel in the LayoutDemo program that demonstrates
      //  the box layout manager.
      //********************************************************************
      
      import java.awt.*;
      import javax.swing.*;
      
      public class BoxPanel extends JPanel
      {
         //-----------------------------------------------------------------
         //  Sets up this panel with some buttons to show how a vertical
         //  box layout (and invisible components) affects their position.
         //-----------------------------------------------------------------
         public BoxPanel()
         {
            setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
      
            setBackground (Color.green);
      
            JButton b1 = new JButton ("BUTTON 1");
            JButton b2 = new JButton ("BUTTON 2");
            JButton b3 = new JButton ("BUTTON 3");
            JButton b4 = new JButton ("BUTTON 4");
            JButton b5 = new JButton ("BUTTON 5");
      
            add (b1);  
            add (Box.createRigidArea (new Dimension (0, 10)));
            add (b2);
            add (Box.createVerticalGlue());
            add (b3);
            add (b4);
            add (Box.createRigidArea (new Dimension (0, 20)));
            add (b5);
         }
      }
        

      CardLayout

      A picture of a GUI that uses CardLayout Another picture of the same layout

      The CardLayout class lets you implement an area that contains different components at different times. A CardLayout is often controlled by a combo box, with the state of the combo box determining which panel (group of components) the CardLayout displays. An alternative to using CardLayout is using a tabbed pane which provides similar functionality but with a pre-defined GUI.

      FlowLayout

      A picture of a GUI that uses FlowLayout

      FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row, starting a new row if its container isn't sufficiently wide. Both panels in CardLayoutDemo, shown previously, use FlowLayout.

      //********************************************************************
      //  FlowPanel.java       Authors: Lewis/Loftus
      //
      //  Represents the panel in the LayoutDemo program that demonstrates
      //  the flow layout manager.
      //********************************************************************
      
      import java.awt.*;
      import javax.swing.*;
      
      public class FlowPanel extends JPanel
      {
         //-----------------------------------------------------------------
         //  Sets up this panel with some buttons to show how flow layout
         //  affects their position.
         //-----------------------------------------------------------------
         public FlowPanel ()
         {
            setLayout (new FlowLayout());
      
            setBackground (Color.green);
      
            JButton b1 = new JButton ("BUTTON 1");
            JButton b2 = new JButton ("BUTTON 2");
            JButton b3 = new JButton ("BUTTON 3");
            JButton b4 = new JButton ("BUTTON 4");
            JButton b5 = new JButton ("BUTTON 5");
      
            add (b1);
            add (b2);
            add (b3);
            add (b4);
            add (b5);
         }
      }
        

      GridBagLayout

      A picture of a GUI that uses GridBagLayout

      GridBagLayout is a sophisticated, flexible layout manager. It aligns components by placing them within a grid of cells, allowing some components to span more than one cell. The rows in the grid can have different heights, and grid columns can have different widths.

      GridLayout

      A picture of a GUI that uses GridLayout

      GridLayout simply makes a bunch of components equal in size and displays them in the requested number of rows and columns.

      //********************************************************************
      //  GridPanel.java       Authors: Lewis/Loftus
      //
      //  Represents the panel in the LayoutDemo program that demonstrates
      //  the grid layout manager.
      //********************************************************************
      
      import java.awt.*;
      import javax.swing.*;
      
      public class GridPanel extends JPanel
      {
         //-----------------------------------------------------------------
         //  Sets up this panel with some buttons to show how grid
         //  layout affects their position, shape, and size.
         //-----------------------------------------------------------------
         public GridPanel()
         {
            setLayout (new GridLayout (2, 3));
      
            setBackground (Color.green);
      
            JButton b1 = new JButton ("BUTTON 1");
            JButton b2 = new JButton ("BUTTON 2");
            JButton b3 = new JButton ("BUTTON 3");
            JButton b4 = new JButton ("BUTTON 4");
            JButton b5 = new JButton ("BUTTON 5");
      
            add (b1);
            add (b2);
            add (b3);
            add (b4);
            add (b5);
         }
      }
      

      SpringLayout

      A picture of a GUI that uses SpringLayout

      Another GUI that uses SpringLayout

      SpringLayout is a flexible layout manager designed for use by GUI builders. It lets you specify precise relationships between the edges of components under its control. For example, you might define that the left edge of one component is a certain distance (which can be dynamically calculated) from the right edge of a second component.

    12. Border Layout

      //********************************************************************
      //  BorderDemo.java       Authors: Lewis/Loftus
      //
      //  Demonstrates the use of various types of borders.
      //********************************************************************
      
      import java.awt.*;
      import javax.swing.*;
      import javax.swing.border.*;
      
      public class BorderDemo
      {
         //-----------------------------------------------------------------
         //  Creates several bordered panels and displays them.
         //-----------------------------------------------------------------
         public static void main (String[] args)
         {
            JFrame frame = new JFrame ("Border Demo");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      
            JPanel panel = new JPanel();
            panel.setLayout (new GridLayout (0, 2, 5, 10));
            panel.setBorder (BorderFactory.createEmptyBorder (8, 8, 8, 8));
      
            JPanel p1 = new JPanel();
            p1.setBorder (BorderFactory.createLineBorder (Color.red, 3));
            p1.add (new JLabel ("Line Border"));
            panel.add (p1);
      
            JPanel p2 = new JPanel();
            p2.setBorder (BorderFactory.createEtchedBorder ());
            p2.add (new JLabel ("Etched Border"));
            panel.add (p2);
      
            JPanel p3 = new JPanel();
            p3.setBorder (BorderFactory.createRaisedBevelBorder ());
            p3.add (new JLabel ("Raised Bevel Border"));
            panel.add (p3);
      
            JPanel p4 = new JPanel();
            p4.setBorder (BorderFactory.createLoweredBevelBorder ());
            p4.add (new JLabel ("Lowered Bevel Border"));
            panel.add (p4);
      
            JPanel p5 = new JPanel();
            p5.setBorder (BorderFactory.createTitledBorder ("Title"));
            p5.add (new JLabel ("Titled Border"));
            panel.add (p5);
      
            JPanel p6 = new JPanel();
            TitledBorder tb = BorderFactory.createTitledBorder ("Title");
            tb.setTitleJustification (TitledBorder.RIGHT);
            p6.setBorder (tb);
            p6.add (new JLabel ("Titled Border (right)"));
            panel.add (p6);
      
            JPanel p7 = new JPanel();
            Border b1 = BorderFactory.createLineBorder (Color.blue, 2);
            Border b2 = BorderFactory.createEtchedBorder ();
            p7.setBorder (BorderFactory.createCompoundBorder (b1, b2));
            p7.add (new JLabel ("Compound Border"));
            panel.add (p7);
      
            JPanel p8 = new JPanel();
            Border mb = BorderFactory.createMatteBorder (1, 5, 1, 1,
                                                         Color.red);
            p8.setBorder (mb);
            p8.add (new JLabel ("Matte Border"));
            panel.add (p8);
      
            frame.getContentPane().add (panel);
            frame.pack();
            frame.setVisible(true);
         }
      }
      

    13. Containment Hierarchies

      Containment hierarchy -- the way components are grouped into containers, and the way those containers are nested within each other. It is a tree of components that has a top-level container as its root.

      Using Top-Level Containers

      Swing provides three generally useful top-level container classes: JFrame, JDialog, and JApplet. When using these classes, you should keep these facts in mind:
      • To appear onscreen, every GUI component must be part of a containment hierarchy.

      • Each GUI component can be contained only once. If a component is already in a container and you try to add it to another container, the component will be removed from the first container and then added to the second.

      • Each top-level container has a content pane that, generally speaking, contains (directly or indirectly) the visible components in that top-level container's GUI.

      • You can optionally add a menu bar to a top-level container. The menu bar is by convention positioned within the top-level container, but outside the content pane.

      Example
      import java.awt.*;
      import java.awt.event.*;
      import javax.swing.*;
      
      /* TopLevelDemo.java requires no other files. */
      public class TopLevelDemo {
          /**
           * Create the GUI and show it.  For thread safety,
           * this method should be invoked from the
           * event-dispatching thread.
           */
          private static void createAndShowGUI() {
              //Make sure we have nice window decorations.
              JFrame.setDefaultLookAndFeelDecorated(true);
      
              //Create and set up the window.
              JFrame frame = new JFrame("TopLevelDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      
              //Create the menu bar.  Make it have a cyan background.
              JMenuBar cyanMenuBar = new JMenuBar();
              cyanMenuBar.setOpaque(true);
              cyanMenuBar.setBackground(Color.cyan);
              cyanMenuBar.setPreferredSize(new Dimension(200, 20));
      
              //Create a yellow label to put in the content pane.
              JLabel yellowLabel = new JLabel();
              yellowLabel.setOpaque(true);
              yellowLabel.setBackground(Color.yellow);
              yellowLabel.setPreferredSize(new Dimension(200, 180));
      
              //Set the menu bar and add the label to the content pane.
              frame.setJMenuBar(cyanMenuBar);
              frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
      
              //Display the window.
              frame.pack();
              frame.setVisible(true);
          }
      
          public static void main(String[] args) {
              //Schedule a job for the event-dispatching thread:
              //creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                  public void run() {
                      createAndShowGUI();
                  }
              });
          }
      }
      

      TopLevelDemo

      A diagram of the frame's major parts

      Containment hierarchy.

      Although the example uses a JFrame in a standalone application, the same concepts apply to JApplets and JDialogs.

      Top-Level Containers and Containment Hierarchies

      Each program that uses Swing components has at least one top-level container. This top-level container is the root of a containment hierarchy — the hierarchy that contains all of the Swing components that appear inside the top-level container.

      As a rule, a standalone application with a Swing-based GUI has at least one containment hierarchy with a JFrame as its root. For example, if an application has one main window and two dialogs, then the application has three containment hierarchies, and thus three top-level containers. One containment hierarchy has a JFrame as its root, and each of the other two has a JDialog object as its root.

      A Swing-based applet has at least one containment hierarchy, exactly one of which is rooted by a JApplet object. For example, an applet that brings up a dialog has two containment hierarchies. The components in the browser window are in a containment hierarchy rooted by a JApplet object. The dialog has a containment hierarchy rooted by a JDialog object.

      Adding Components to the Content Pane

      Here's the code that the preceding example uses to get a frame's content pane and add the yellow label to it:
      frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
      
      As the code shows, you find the content pane of a top-level container by calling the getContentPane method. The default content pane is a simple intermediate container that inherits from JComponent, and that uses a BorderLayout as its layout manager.

      It's easy to customize the content pane — setting the layout manager or adding a border, for example. However, there is one tiny gotcha. The getContentPane method returns a Container object, not a JComponent object. This means that if you want to take advantage of the content pane's JComponent features, you need to either typecast the return value or create your own component to be the content pane. Our examples generally take the second approach, since it's a little cleaner. Another approach we sometimes take is to simply add a customized component to the content pane, covering the content pane completely.

      If you create your own content pane, make sure it's opaque. An opaque JPanel object makes a good content pane. Note that the default layout manager for JPanel is FlowLayout; you'll probably want to change it.

      To make a component the content pane, use the top-level container's setContentPane method. For example:

      
      //Create a panel and add components to it.
      JPanel contentPane = new JPanel(new BorderLayout());
      contentPane.setBorder(someBorder);
      contentPane.add(someComponent, BorderLayout.CENTER);
      contentPane.add(anotherComponent, BorderLayout.PAGE_END);
      
      //Make it the content pane.
      contentPane.setOpaque(true);
      topLevelContainer.setContentPane(contentPane);
      

      Note:  Don't use non-opaque containers such as JScrollPane, JSplitPane, and JTabbedPane as content panes. A non-opaque content pane results in messy repaints. Although you can make any Swing component opaque by invoking setOpaque(true) on it, some components don't look right when they're completely opaque. For example, tabbed panes generally let part of the underlying container show through, so that the tabs look non-rectangular. An opaque tabbed pane just tends to look bad.

      In most look and feels, JPanels are opaque by default. However, JPanels in the GTK+ look and feel, which was introduced in 1.4.2, are not initially opaque. To be safe, we invoke setOpaque on all JPanels used as content panes.


      Adding a Menu Bar

      All top-level containers can, in theory, have a menu bar. In practice, however, menu bars usually appear only in frames and perhaps in applets. To add a menu bar to a top-level container, you create a JMenuBar object, populate it with menus, and then call setJMenuBar. The TopLevelDemo adds a menu bar to its frame with this code:
      frame.setJMenuBar(cyanMenuBar);
      

      The Root Pane

      Each top-level container relies on a reclusive intermediate container called the root pane. The root pane manages the content pane and the menu bar, along with a couple of other containers. You generally don't need to know about root panes to use Swing components. However, if you ever need to intercept mouse clicks or paint over multiple components, you should get acquainted with root panes.

      Here's a glimpse at the components that a root pane provides to a frame (and to every other top-level container):

      A root pane manages four other panes: a layered pane, a menu bar, a content pane, and a glass pane.

    14. The glass pane
      Hidden, by default. If you make the glass pane visible, then it's like a sheet of glass over all the other parts of the root pane. It's completely transparent unless you implement the glass pane's paintComponent method so that it does something, and it intercepts input events for the root pane. In the next section, you'll see an example of using a glass pane.

    15. The layered pane
      Serves to position its contents, which consist of the content pane and the optional menu bar. Can also hold other components in a specified Z order. For information, see The Layered Pane. The content pane
      The container of the root pane's visible components, excluding the menu bar. For information on using the content pane, see Using Top-Level Containers.

    16. The optional menu bar
      The home for the root pane's container's menus. If the container has a menu bar, you generally use the container's setJMenuBar method to put the menu bar in the appropriate place. For more information on using menus and menu bars, see How to Use Menus.
    17. Component Class Hierarchy

      All of the Java classes that define GUI components are part of a class hierarchy:

        Component  
         
        Container  
         
        JComponent  
         
      ________________________________________________________________________
      JPanel
       
        JAbstracButton  
      _________________________
        JButton
         
       
      JLabel
       
      JTextComponent
      JTextField