Java: Frame Tricks

Posted on

These are rather tiny and mundane JFrame tricks, but nice to have in your bag of useful Swing tools when coding. These methods help center a window on screen, maximize, minimize and restore a window. Simple yet powerful.

public void center(Window w) {
	int screenWidth  = Toolkit.getDefaultToolkit().getScreenSize().width;
	int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;

	int windowWidth = w.getWidth();
	int windowHeight = w.getHeight();

	if (windowHeight > screenHeight) {

	if (windowWidth > screenWidth) {

	int x = (screenWidth - windowWidth) / 2;
	int y = (screenHeight - windowHeight) / 2;

	w.setLocation(x, y);

public void maximizeFrame(Frame frame) {

public void iconifyFrame(Frame frame) {

public void restoreFrame(Frame frame) {

public int getScreenHeight() {
	return Toolkit.getDefaultToolkit().getScreenSize().height;

public int getScreenWidth() {
	return Toolkit.getDefaultToolkit().getScreenSize().width;

Leave a Comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s