
Save Window Settings #37
Chapter 5, Windows, Dialogs, and Frames
|
193
HACK
—Jonathan Simon
H A C K
#37
Save Window Settings Hack #37
Make sure your windows always show up right where you left them, even
after a program restarts, by saving the window position and size
automatically.
Swing is a rich toolkit that can be used to create many kinds of programs,
but there are certain features that virtually all applications need, like win-
dow settings and preferences. This hack shows how to automatically store
and retrieve window locations and dimensions in an existing program with-
out using custom
Frame subclasses, or even making many changes to your
existing code.
Saving the size and location of a window is actually pretty easy. You can just
store them in a file and retrieve them later. The difficulty is identifying each
window, and doing it in a way that’s as noninvasive as possible.
The Window Saver Class
The first step is to create a class that handles all of the work. Because man-
aging windows will be a global function of the entire program, start with a
simple singleton with a factory interface, as shown in Example 5-4.
JLabel dateLabel = new JLabel("12/31/99");
dateLabel.setHorizontalAlignment(SwingConstants.CENTER);
statusBar.addRightComponent(dateLabel, 30);
JLabel timeLabel = new JLabel("11:59 PM");
timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
statusBar.addRightComponent(timeLabel, ...