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 16. (Advanced topics) Desktops and Internal Frames. Easy for reading, Click here!

Custom Search
Swing Chapter 16. (Advanced topics) Desktops and Internal Frames. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 3/5 



Previous Page Previous Page (2/5) - Next Page (4/5) Next Page
Subpages: 1. JDesktopPane and JInternalFrame 
2.
Internalizable/Externalizable frames 
3.
Cascading and outline dragging mode 
4. An X windows style desktop environment 
5. A networked multi-user desktop using sockets 

16.3  Cascading and outline dragging mode

You are most likely familiar with the cascading layout that occurs as new windows are opened in MDI environments. In fact, if you have looked at any of the custom MDI examples of chapter 15 you will have seen that when you start each demo the InnerFrames are arranged in a cascaded fashion. This example shows how to control cascading for an arbitrary number of internal frames. Additionaly, the ability to switch between any pluggable L&F available on your system is added, and outline dragging mode is enabled in our desktop.

Figure 16.3 Cascading Internal Frames

<<file figure16-3.gif>>

The Code: CascadeDemo.java

see \Chapter16\1

import java.beans.PropertyVetoException;

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class CascadeDemo extends JFrame implements ActionListener

{

  private static ImageIcon EARTH;

  private int m_count;

  private int m_tencount;

  private JButton m_newFrame;

  private JDesktopPane m_desktop;

  private JComboBox m_UIBox;

  private UIManager.LookAndFeelInfo[] m_infos;

  public CascadeDemo() {

    super("CascadeDemo");

    EARTH = new ImageIcon("earth.jpg");

    m_count = m_tencount = 0;

    m_desktop = new JDesktopPane();

    m_desktop.putClientProperty(

      "JDesktopPane.dragMode","outline");

    m_newFrame = new JButton("New Frame");

    m_newFrame.addActionListener(this);

    m_infos = UIManager.getInstalledLookAndFeels();

    String[] LAFNames = new String[m_infos.length];

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

      LAFNames[i] = m_infos[i].getName();

    }

    m_UIBox = new JComboBox(LAFNames);

    m_UIBox.addActionListener(this);

    JPanel topPanel = new JPanel(true);

    topPanel.add(m_newFrame);

    topPanel.add(new JLabel("Look & Feel:",SwingConstants.RIGHT));

    topPanel.add(m_UIBox);

    getContentPane().setLayout(new BorderLayout());

    getContentPane().add("North", topPanel);

    getContentPane().add("Center", m_desktop);

    setSize(570,400);

    Dimension dim = getToolkit().getScreenSize();

    setLocation(dim.width/2-getWidth()/2,

      dim.height/2-getHeight()/2);

    setVisible(true);

    WindowListener l = new WindowAdapter() {

      public void windowClosing(WindowEvent e) {

        System.exit(0);

      }

    };       

    addWindowListener(l);

  }

  public void newFrame() {

    JInternalFrame jif = new JInternalFrame("Frame " + m_count,

      true, true, true, true);

    jif.setBounds(20*(m_count%10) + m_tencount*80,

      20*(m_count%10), 200, 200);

    JLabel label = new JLabel(EARTH);

    jif.getContentPane().add(new JScrollPane(label));

    m_desktop.add(jif);

    try {            

      jif.setSelected(true);        

    }

    catch (PropertyVetoException pve) {

      System.out.println("Could not select " + jif.getTitle());

    }

    m_count++;

    if (m_count%10 == 0) {

      if (m_tencount < 3)

        m_tencount++;

      else

        m_tencount = 0;

    }

  }

  public void actionPerformed(ActionEvent e) {

    if (e.getSource() == m_newFrame)

      newFrame();

    else if (e.getSource() == m_UIBox) {  

      m_UIBox.hidePopup(); // BUG WORKAROUND

      try {

        UIManager.setLookAndFeel(

          m_infos[m_UIBox.getSelectedIndex()].getClassName());

        SwingUtilities.updateComponentTreeUI(this);

      }

      catch(Exception ex) {

        System.out.println("Could not load " +

          m_infos[m_UIBox.getSelectedIndex()].getClassName());

      }

    }

  }

  public static void main(String[] args) {

    new CascadeDemo();

  }

}

Understanding the Code

Class CascadeDemo

CascadeDemo extends JFrame to provide the main container for this example. The constructor is responsible for initializing and laying out all GUI components. One class variable, EARTH, and several instance variables are needed:

ImageIcon EARTH: image used in each JLabel.

int m_count: keeps track of the number of internal frames that exist within the desktop.

int m_tencount: incremented every time ten internal frames are added to the desktop.

JButton m_newFrame: used to add new JInternalFrames to m_desktop.

JDesktopPane m_desktop: container for our JInternalFrames.

JComboBox m_UIBox: used for L&F selection.

UIManager.LookAndFeelInfo[] m_infos: An array of LookAndFeelInfo objects used in changing L&Fs.

The only code that may look unfamiliar to you in the constructor is the following:

    m_infos = UIManager.getInstalledLookAndFeels();

    String[] LAFNames = new String[m_infos.length];

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

      LAFNames[i] = m_infos[i].getName();

    }

    m_UIBox = new JComboBox(LAFNames);

The UIManager class is in charge of keeping track of the current look and feel as well as providing us with a way to query information about the different look and feels available on our system. Its static getInstalledLookAndFeels() method returns an array of UIManager.LookAndFeelInfo objects and we assign this array to m_infos.

Each UIManager.LookAndFeelInfo object represents a different look-and-feel that is currently installed on our system. Its getName() method returns a short  name representing its associated look and feel (e.g. "Metal", "CDE/Motif", "Windows", etc.). We create an array of these Strings, LAFNames, with indices corresponding to those of m_infos.

Finally we create a JComboBox, m_UIBox, using this array of Strings. In the actionPerformed() method (see below) when an entry in m_UIBox is selected we match it with its corresponding UIManager.LookAndFeelInfo object in m_infos and load the associated look-and-feel.

The newFrame method is invoked whenever m_NewButton is pressed. First this method creates a new JInternalFrame with resizable, closable, maximizable, and iconifiable properties, and a unique title based on the current frame count:

    JInternalFrame jif = new JInternalFrame("Frame " + m_count,

      true, true, true, true);

The frame is then sized to 200 x 200 and its initial position within the our desktop is calculated based on the value of m_count and  m_tencount. The value of m_tencount is periodically reset so that each new internal frame lies within our desktop view (assuming we do not resize our desktop to have a smaller width than the maximum of 20*(m_count%10) + m_tencount*80, and a smaller height than the maximum of 20*(m_count%10). This turns out to be 420 x 180, where the maximum of m_count%10 is 9 and the maximum of m_tencount is 3).

    jif.setBounds(20*(m_count%10) + m_tencount*80,

      20*(m_count%10), 200, 200);

Note: You might imagine a more flexible cascading scheme that positions internal frames based on the current size of the desktop. In general a rigid cascading routine is sufficient, but we are certainly not limited to this.

A JLabel with an image is added to a JScrollPane, which is then added to the contentPane of each internal frame. Each frame is added to the desktop in layer 0 (the default layer when none is specified). Note that adding an internal frame to the desktop does not automatically place that frame at the frontmost position within the specified layer, and it is not automatically selected. To force both of these things to occur we use the JInternalFrame setSelected() method (which requires us to catch a java.beans.PropertyVetoException).

Finally the newFrame() method increments m_count and determines whether to increment m_tencount or reset it to 0. m_tencount is only incremented after a group of 10 frames has been added (m_count%10 == 0) and is only reset after it has reached a value of 3. So 40 internal frames are created for each cycle of m_tencount (10 for m_tencount = 0, 1, 2, and 3).

    m_count++;

    if (m_count%10 == 0) {

      if (m_tencount < 3)

        m_tencount++;

      else

        m_tencount = 0;

    }

The actionPerformed() method handles m_newFrame button presses and m_UIBox selections. The m_newFrame button invokes the newFrame() method and selecting a look and feel from m_UIBox changes the application to use that L&F. Look-and-feel switching is done by calling the UIManager setLookAndFeel() method and passing it the classname of the L&F to use (which we stored in the m_infos array in the constructor). Calling SwingUtilities.updateComponentTreeUI(this) changes the look and feel of everything contained within the CascadeDemo frame (refer back to chapter 2).

Bug Alert: The call to m_UIBox.hidePopup() is added to avoid a null pointer exception bug that is caused when changing the look-and-feel of an active JComboBox. We expect this to be fixed in a future Java 2 release.

Running the Code: 

Figure 16.2 shows CascadeDemo in action. This figure shows a JInternalFrame in the process of being dragged in outline dragging mode. Try creating plenty of frames to make sure that cascading is working properly. Experiment with different L&Fs. As a final test comment out the m_UIBox.hidePopup() call to check if this bug has been fixed in your version of Java.



[ 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