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
now makes it possible with JDesktopPane
and
JInternalFrame
. Figure 15.10
shows how this works.
You get
a lot of behavior for free from
JInternalFrame
. Internal frames can be moved by
clicking and dragging the title bar. 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
application’s data inside an internal frame.
The following brief example shows how to create the windows shown in Figure 15.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) { // create a JFrame to hold everything JFrame f = new JFrame("Desktop"); f.addWindowListener(new WindowAdapter( ) { public void windowClosing(WindowEvent we) { System.exit(0); } }); f.setSize(300, 300); f.setLocation(200, 200); 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); } f.setContentPane(desktop); f.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
internal-FrameClosing( )
method. This is just like defining the windowClosing( )
method for
a JFrame
.
Get Learning Java now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.