Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

Swing Chapter 15. (Advanced topics) Layered Panes and custom MDI. Easy for reading, Click here!

Custom Search
Swing Chapter 15. (Advanced topics) Layered Panes and custom MDI. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 6/7 



Previous Page Previous Page (5/7) - Next Page (7/7) Next Page
Subpages: 1. JLayeredPane 
2.
Using JLayeredPane to enhance interfaces 
3.
Creating a custom MDI: part I - Dragging panels 
4. Creating a custom MDI: part II - Resizability 
5. Creating a custom MDI: part III - Enhancements 
6. Creating a custom MDI: part IV - Selection and management 
7. Creating a custom MDI: part V - JavaBeans compliance 

15.6  Creating a custom MDI: part IV - Selection and management

When we resize our JFrame it would be nice if iconified frames lined up and stayed at the bottom. This would prevent them from being lost from the layered pane view, and would also increase the organized feel of our MDI. Similarly, when an InnerFrame is maximized it should always fill the entire viewable region of its parent. Thus, it would be nice to have some way of controlling the layout of our InnerFrames when the parent is resized. We can do this by extending JLayeredPane and implementing the java.awt.event.ComponentListener interface to listen for resize ComponentEvents. We can capture and handle events sent to the componentResized() method to lay out iconified frames and resize maximized frames in a manner similar to most modern MDI environments. (Note that we could also extend ComponentAdapter and use an instance of the resulting class as a ComponentListener attached to our JLayeredPane. As is often the case, there is more than one way to implement the functionality we are looking for for.) In this section we'll build a JLayeredPane subclass that implements ComponentListener, and add it to our mdi package.

Another limiting characteristic of InnerFrame is that the only way to get the focus, and to move an InnerFrame to the front of the layered pane view, is to click on its title bar. Ideally, clicking anywhere on an InnerFrame should move it to the front of the layered pane view. This is where JRootPane's glassPane comes in handy. Since our InnerFrames now contain a JRootPane as their main container we can use the glassPane to intercept mouse events and move the selected InnerFrame to the front. We will need to make our glassPane completely transparent, and it should only be active (i.e. receiving mouse events) within an InnerFrame when that InnerFrame is not in the foremost position of its layer (see section 15.1). Thus, only one InnerFrame per layer should have an inactive glassPane. This one frame is the selected InnerFrame--the one with the current user focus.

It is customary to visually convey to the user which frame is selected. We will do this by adding a new boolean property to our InnerFrame representing whether or not it is selected. We will manipulate this property in such a way that there can be only one selected InnerFrame per layer. A selected InnerFrame will be characterised by unique border and title bar colors.

Figure 15.9. Custom MDI: part IV

<<file figure15-9.gif>>

The Code: InnerFrame.java

see \Chapter15\5\mdi

package mdi;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

import javax.swing.border.EmptyBorder;

public class InnerFrame

extends JPanel implements RootPaneContainer

{

  // Unchanged code

  private static Color DEFAULT_TITLE_BAR_BG_COLOR =

    new Color(108,190,116);

  private static Color DEFAULT_BORDER_COLOR =

    new Color(8,90,16);

  private static Color DEFAULT_SELECTED_TITLE_BAR_BG_COLOR =

    new Color(91,182,249);

  private static Color DEFAULT_SELECTED_BORDER_COLOR =

    new Color(0,82,149);

  private Color m_titleBarBackground =

    DEFAULT_TITLE_BAR_BG_COLOR;

  private Color m_titleBarForeground = Color.black;

  private Color m_BorderColor = DEFAULT_BORDER_COLOR;

  private Color m_selectedTitleBarBackground =

    DEFAULT_SELECTED_TITLE_BAR_BG_COLOR;

  private Color m_selectedBorderColor =

    DEFAULT_SELECTED_BORDER_COLOR;

  private boolean m_selected;

  // Unchanged code

  protected void setupCapturePanel() {

    CapturePanel mouseTrap = new CapturePanel();

    m_rootPane.getLayeredPane().add(mouseTrap,

      new Integer(Integer.MIN_VALUE));

    mouseTrap.setBounds(0,0,10000,10000);

    setGlassPane(new GlassCapturePanel());

    getGlassPane().setVisible(true);

  }

  // Unchanged code

  public void toFront() {

    if (getParent() instanceof JLayeredPane)

      ((JLayeredPane) getParent()).moveToFront(this);

    if (!isSelected())

      setSelected(true);

  }

  // Unchanged code

  public boolean isSelected() {

    return m_selected;

  }

  public void setSelected(boolean b) {

    if (b)

    {

      if (m_selected != true &&

        getParent() instanceof JLayeredPane)

      {

        JLayeredPane jlp = (JLayeredPane) getParent();

        int layer = jlp.getLayer(this);

        Component[] components = jlp.getComponentsInLayer(layer);

        for (int i=0; i<components.length; i++) {

          if (components[i] instanceof InnerFrame) {

            InnerFrame tempFrame = (InnerFrame) components[i];

            if (!tempFrame.equals(this))

              tempFrame.setSelected(false);

          }

        }

        m_selected = true;

        updateBorderColors();

        updateTitleBarColors();

        getGlassPane().setVisible(false);

        repaint();

      }

    }

    else

    { 

      m_selected = false;

      updateBorderColors();

      updateTitleBarColors();

      getGlassPane().setVisible(true);

      repaint();

    }

  }

  ////////////////////////////////////////////

  //////////////// Title Bar /////////////////

  ////////////////////////////////////////////

  public void setTitleBarBackground(Color c) {

    m_titleBarBackground = c;

    updateTitleBarColors();

  }

  public Color getTitleBarBackground() {

    return m_titleBarBackground;

  }

  public void setTitleBarForeground(Color c) {

    m_titleBarForeground = c;

    m_titleLabel.setForeground(c);

    m_titlePanel.repaint();

  }

  public Color getTitleBarForeground() {

    return m_titleBarForeground;

  }

  public void setSelectedTitleBarBackground(Color c) {

    m_titleBarBackground = c;

    updateTitleBarColors();

  }

  public Color getSelectedTitleBarBackground() {

    return m_selectedTitleBarBackground;

  }

  protected void updateTitleBarColors() {

    if (isSelected())

      m_titlePanel.setBackground(m_selectedTitleBarBackground);

    else

      m_titlePanel.setBackground(m_titleBarBackground);

  }

  // Unchanged code

  protected void createTitleBar() {

    // Unchanged code

    m_titleLabel.setForeground(m_titleBarForeground);

  }

  // Unchanged code

  ///////////////////////////////////////////////

  ///////////// GlassPane Selector //////////////

  ///////////////////////////////////////////////

  class GlassCapturePanel extends JPanel

  {

    public GlassCapturePanel() {

      MouseInputAdapter mia = new MouseInputAdapter() {

        public void mousePressed(MouseEvent e) {

          InnerFrame.this.toFront();

        }

      };

      addMouseListener(mia);

      addMouseMotionListener(mia);

      setOpaque(false);

    }

  }

  ///////////////////////////////////////////////

  //////////////// Resizability /////////////////

  ///////////////////////////////////////////////

  public void setBorderColor(Color c) {

    m_BorderColor = c;

    updateBorderColors();

  }

  public Color getBorderColor() {

    return m_BorderColor;

  }

  public void setSelectedBorderColor(Color c) {

    m_selectedBorderColor = c;

    updateBorderColors();

  }

  public Color getSelectedBorderColor() {

    return m_selectedBorderColor;

  }

  protected void updateBorderColors() {

    if (isSelected()) {

      m_northResizer.setBackground(m_selectedBorderColor);

      m_southResizer.setBackground(m_selectedBorderColor);

      m_eastResizer.setBackground(m_selectedBorderColor);

      m_westResizer.setBackground(m_selectedBorderColor);

    } else {

      m_northResizer.setBackground(m_BorderColor);

      m_southResizer.setBackground(m_BorderColor);

      m_eastResizer.setBackground(m_BorderColor);

      m_westResizer.setBackground(m_BorderColor);

    }

  }

  // Unchanged code

}

The Code: MDIPane.java

see \Chapter15\5\mdi

package mdi;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class MDIPane

extends JLayeredPane

implements ComponentListener

{

  public MDIPane() {

    addComponentListener(this);

    setOpaque(true);

    // default background color

    setBackground(new Color(244,232,152));

  }

  public void componentHidden(ComponentEvent e) {}

  public void componentMoved(ComponentEvent e) {}

  public void componentShown(ComponentEvent e) {}

  public void componentResized(ComponentEvent e) { lineup(); }

  public void lineup() {

    int frameHeight, frameWidth, currentX,

      currentY, lheight, lwidth;

    lwidth = getWidth();

    lheight = getHeight();

    currentX = 0;

    currentY = lheight;

    Component[] components = getComponents();

    for (int i=components.length-1; i>-1; i--) {

      if (components[i] instanceof InnerFrame) {

        InnerFrame tempFrame = (InnerFrame) components[i];

        frameHeight = tempFrame.getHeight();

        frameWidth = tempFrame.getWidth();

        if (tempFrame.isMaximized()) {

          tempFrame.setBounds(0,0,getWidth(),getHeight());

          tempFrame.validate();

          tempFrame.repaint();

        }

        else if (tempFrame.isIconified()) {

          if (currentX+frameWidth > lwidth) {

            currentX = 0;

            currentY -= frameHeight;

          }

          tempFrame.setLocation(currentX, currentY-frameHeight);

          currentX += frameWidth;

        }

      }

    }

  }

}

Understanding The Code:

Class LayeredPaneDemo

The only changes that have been made to this class is the replacement of the default JLayeredPane in our application frame with an instance of our custom MDIPane (see below).

Class InnerFrame

The following class variables have been added:

Color DEFAULT_TITLE_BAR_BG_COLOR: default title bar background.

Color DEFAULT_BORDER_COLOR: default border background.

Color DEFAULT_SELECTED_TITLE_BAR_BG_COLOR: default selected title bar background.

Color DEFAULT_SELECTED_BORDER_COLOR: default selected frame border.

New instance variables:

Color m_titleBarBackground: current title bar background.

Color m_titleBarForeground: current title bar foreground.

Color m_BorderColor: current border.

Color m_selectedTitleBarBackground: current selected title bar background.

Color m_selectedBorderColor: current selected border background.

boolean m_selected: true when frame is selected.

The setupCapturePanel() method now adds a call to set InnerFrame's glassPane to an instance of our custom class GlassCapturePanel (see below). This allows selection via clicking on any region of an inactive InnerFrame.

We've inserted an additional check in the toFront() method to call setSelected(true) if that frame is not already selected:

    if (!isSelected())

      setSelected(true);

The isSelected() method has been added to simply return the current value of m_selected, and method setSelected() is what actually controlls this property.

Method setSelected() takes a boolean value representing whether the frame should be selected or de-selected. If it is to be selected and it resides in a JLayeredPane, this method searches for all other InnerFrame siblings in the same layer of that JLayeredPane and calls setSelected(false) on each one it finds. Then we set the current InnerFrame's selected property, m_selected, to true and call updateBorderColors() and updateTitleBarColors() (see below) to visually convey that this is the selected frame:

      m_selected = true;

      updateBorderColors();

      updateTitleBarColors();

      getGlassPane().setVisible(false);

      repaint();

The glassPane is hidden whenever a frame is selected so that mouse events will no longer be trapped (see GlassCapturePanel below). When a frame is de-selected (i.e. setSelected(false) has been called), this method disables its selected property, calls the updateXXColors() methods, and brings its glassPane out of hiding so that it may intercept mouse events for future selection:

      m_selected = false;

      updateBorderColors();

      updateTitleBarColors();

      getGlassPane().setVisible(true);

      repaint();

This whole scheme provides us with a guarantee that only one InnerFrame will be selected per JLayeredPane layer.

Methods setTitleBarBackground(), setTitleBarForeground(), and setSelectedTitleBarBackground() have all been added to manage the state of the current title bar color properties. Each of these methods calls updateTitleBarColors() so that the changes made are actually applied to the title bar and border components. In the JavaBeans spirit, we've also added get() methods to retreive these properties.

Similarly, methods setBorderColor(), setSelectedBorderColor(), updateBorderColors(), and associated get() methods, to manage the border color properties. The updateBorderColors() method is responsible for applying these colors to each of the resize edge components.

Class mdi.InnerFrame.GlassCapturePanel

This class is almost identical to our CapturePanel inner class. The only difference is that its MouseInputAdapter overrides the mousePressed() method to call toFront() on the associated InnerFrame.

        public void mousePressed(MouseEvent e) {

          InnerFrame.this.toFront();

        }

As we saw above, toFront() calls setSelected() as necessary. Instances of this class are used as the glassPane of each InnerFrame's JRootPane. GlassCapturePanel is active (visible) when its parent InnerFrame is not selected. It is inactive (hidden) when the associated InnerFrame is selected. This activation is controlled by the setSelected() method, as we saw above. The only function of this component is to provide a means of switching InnerFrame selection by clicking on any portion of an unselected InnerFrame.

Class mdi.MDIPane

This class extends JLayeredPane and implements the java.awt.event.ComponentListener interface. Whenever this component is resized the componentResized() method is invoked. This method invokes lineup()which grabs an array of all Components within the MDIPane. We then loop through this array, each time checking whether the Component at the current index is an instance of InnerFrame.

    Component[] components = getComponents();

    for (int i=components.length-1; i>-1; i--) {

      if (components[i] instanceof InnerFrame) {

If it is we then check if it is maximized or iconified. If it is maximized we reset its bounds to completely fill the visible region of the MDIPane. If it is iconified we place it at the bottom of the layered pane. This method locally maintains the position where the next iconified frame should be placed (currentX and currentY) and places these frames in rows, stacked from bottom up, that completely fit within MDIPane's horizontal visible region (refer back to the code for details).

Running The Code

Figure 5.9 shows LayeredPaneDemo in action. Iconify the InnerFrames and adjust the size of the application frame to see the layout change. Now maximize an InnerFrame and adjust the size of the JFrame to see that the InnerFrame is resized appropriately. You may also want to experiment with the LayeredPaneDemo constructor and add another set or two of InnerFrames to different layers. You will see that there can only be one selected InnerFrame per layer, as expected.

This method of organizing iconified frames is certainly not adequate for professional implementations. However, developing it any further would take us a bit too far into the details of MDI construction. Ideally we might implement some sort of manager that InnerFrames and MDIPane can use to communicate with one another. (In the next chapter we will discuss a class called DesktopManager which functions as such a communications bridge between JDesktopPane and its JInternalFrame children. We will also learn that such a manager, as simple as it is, provides us with a great deal of flexibility.)



[ Return to Swing (Book) ]


Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color


[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3


[ More in News Section ]


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy