Desktops

At this point, you might be thinking that there's nothing more that Swing could possibly do, but it just keeps getting better. If you've ever wished that you could have windows within windows in Java, Swing makes it possible with JDesktopPane and JInternalFrame. Screenshot-10 shows how this works.

Screenshot-10. Using internal frames on a JDesktopPane
Java ScreenShot

You get a lot of behavior for free from JInternalFrame. Internal frames can be moved by clicking and dragging the titlebar. They can be resized by clicking and dragging on the window's borders. Internal frames can be iconified, which means reducing them to a small icon representation on the desktop. Internal frames may also be made to fit the entire size of the desktop (maximized). To you, the programmer, the internal frame is just a kind of special container. You can put your app's data inside an internal frame just as with any other type of container. The following brief example shows how to create the windows shown in Screenshot-10:

 //file: Desktop.java
 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
 import javax.swing.border.*;
 public class Desktop {
 public static void main(String[] args) {
 JFrame frame = new JFrame("Desktop");
 JDesktopPane desktop = new JDesktopPane( );
 for (int i = 0; i < 5; i++) {
 JInternalFrame internal =
 new JInternalFrame("Frame " + i, true, true, true, true);
 internal.setSize(180, 180);
 internal.setLocation(i * 20, i * 20);
 internal.setVisible(true);
 desktop.add(internal);
 }
 frame.setSize(300, 300);
 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
 frame.setContentPane(desktop);
 frame.setVisible(true);
 }
 }


All we've done here is to create a JDesktopPane and add internal frames to it. When each JInternalFrame is constructed, we specify a window title. The four true values passed in the constructor specify that the new window should be resizable, closable, maximizable, and iconifiable. JInternalFrames fire off their own set of events. However, InternalFrameEvent and InternalFrameListener are just like WindowEvent and WindowListener with the names changed. If you want to hear about a JInternalFrame closing, just register an InternalFrameListener and define the internalFrameClosing( )method. This is just like defining the windowClosing( ) method for a JFrame.

Comments