Java Reference
In-Depth Information
Discussion
The code for this is pretty simple. The part that might take a while to figure out is the
Dimen-
sion
of the screen. Two methods can help:
getScreenSize()
in the
Toolkit
class and the
static method
getDefaultToolkit()
. The
Toolkit
class relates to the underlying window-
ing toolkit; it has several subclasses, including two different ones for X Windows on Unix
(Motif and non-Motif), another for Macintosh, and so on. Put these together and you have
the
Dimension
you need.
Centering a
Window
is such a common need that I have packaged it in its own little class:
UtilGUI
. Here is the complete source for
UtilGUI
, which I'll use without comment from
now on:
// package com.darwinsys.swingui;
public
public class
class
UtilGUI
UtilGUI
{
/** Centre a Window, Frame, JFrame, Dialog, etc. */
public
public static
final
Window w
) {
// After packing a Frame or Dialog, centre it on the screen.
Dimension us
=
w
.
getSize
(),
them
=
Toolkit
.
getDefaultToolkit
().
getScreenSize
();
static
void
void
centre
(
final
int
int
newX
= (
them
.
width
-
us
.
width
) /
2
;
int
int
newY
= (
them
.
height
-
us
.
height
)/
2
;
w
.
setLocation
(
newX
,
newY
);
}
/** Center a Window, Frame, JFrame, Dialog, etc.,
* but do it the American Spelling Way :-)
*/
public
public static
static
void
void
center
(
final
final
Window w
) {
UtilGUI
.
centre
(
w
);
}
/** Maximize a window, the hard way. */
public
public static
static
void
void
maximize
(
final
final
Window w
) {
Dimension them
=
Toolkit
.
getDefaultToolkit
().
getScreenSize
();
w
.
setBounds
(
0
,
0
,
them
.
width
,
them
.
height
);
}
/**
* Copy a string value to the system copy buffer
*/