210
|
Chapter 5, Windows, Dialogs, and Frames
#40 Minimize to a Mini-Frame
HACK
The code declares a MiniMizeHack class, which creates the UI and adds itself
as an
ActionListener to the Minimize and Restore menu items. The mouse
listener implementation is there to control the pop-up menu, but because
the
MiniMizeHack
class hasn’t been added as a listener to any components,
the pop up won’t do anything yet.
Minimize the Frame
The actionPerformed( ) method does the actual switching. This is the meat
of the hack. It tests if the bottom component is visible. If the component is
visible, then this method calls
switchToMini( )
and reshapes the frame to be
smaller. If the bottom component is not visible, then
actionPerformed( )
calls
switchToNormal( )
to reverse the changes:
public void actionPerformed(ActionEvent evt) {
if(bottom.isVisible( )) {
switchToMini( );
} else {
switchToNormal( );
}
}
The magic happens in the switchToMini( ) method. A big part of a mini win-
dow is that it doesn’t have any borders, or at the least it uses custom ones.
Swing does not let you turn off a frame’s borders and window decorations
after the frame has been shown on screen because it might have already allo-
cated immutable system resources. The only way around this limitation is to
seamlessly replace the old frame with a new one:
private Dimension normal_size;
public void switchToMini( ) {
// nuke the old frame and build a new one
Point location = frame.getLocation( );
normal_size = frame.getSize( );
frame.setVisible(false);
frame = new JFrame( );
frame.setUndecorated(true);
frame.getContentPane( ).add(panel);
The switchToMini( ) method starts by saving the current frame location and
size, and then hides the frame and replaces it with a new one. Now, it can
safely call
setUndecorated(true) on the frame. The frame.getContentPane( ).
add(panel)
line will add the main panel to the new frame. It is not necessary
to remove the panel from the old frame because Swing will take care of it
automatically. There is also no need to remove the menu bar because it had
never been added to the new frame.
Now, the code can hide the bottom component (the label representing the
extra clock configuration) and add the mouse listener to activate the pop up

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.