Minimize to a Mini-Frame #40
Chapter 5, Windows, Dialogs, and Frames
|
211
HACK
on right-clicks. If you are using Java 5.0, you can add another line to make
the frame always be on top. This can be annoying to some users, however,
so a real program would have a preference to control that feature:
// hide the extra components
bottom.hide( );
// add the pop up
panel.addMouseListener(this);
// stay on top
frame.setAlwaysOnTop(true);
// show the frame again
frame.pack( );
frame.setLocation(location);
frame.setVisible(true);
With the frame prepared, the code packs it, gives it the location of the origi-
nal frame, and makes it visible again.
Restore the Frame
When the user triggers the pop-up menu and selects Normal, the
switchToNormal( ) method will be called. This method reverses what the
switchToMini( ) method did:
public void switchToNormal( ) {
// nuke the old frame and build a new one
Point location = frame.getLocation( );
frame.setVisible(false);
frame = new JFrame( );
frame.setUndecorated(false);
frame.getContentPane( ).add(panel);
// show the extra components
bottom.show( );
frame.setJMenuBar(menubar);
// hide the pop up
panel.removeMouseListener(this);
// turn off stay on top
frame.setAlwaysOnTop(false);
// show the frame again
frame.pack( );
frame.setSize(normal_size);
frame.setLocation(location);
frame.setVisible(true);
}
212
|
Chapter 5, Windows, Dialogs, and Frames
#40 Minimize to a Mini-Frame
HACK
switchToNormal( ) will first save the location of the frame, hide the frame,
and replace it with a new, fully decorated one. It then turns the menu bar
and bottom component back on, removes the pop-up listener, turns off
Always on Top (only for Java 5.0), and restores the frame.
To launch the application, you need to add only a
main( )
method to create a
mini and show it on screen:
public static void main(String[] args) {
MiniMizeHack mini = new MiniMizeHack( );
mini.frame.pack( );
mini.frame.setSize(300,300);
mini.frame.setVisible(true);
}
Swing doesn’t do everything by default, but it makes a lot of things possi-
ble. This hack showed how to create the sort of dynamic frame actions that
users expect today. One enhancement you would probably want to add is
the draggable background
[Hack #34] because a window without a titlebar may
be difficult to move by itself. You might also want to use small buttons
instead of a pop-up menu to control the toggling since most users will be
familiar with the min, max, and close buttons.

Get Swing Hacks 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.