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) {
		return;
	}

	if (windowWidth > screenWidth) {
		return;
	}

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

	w.setLocation(x, y);
}

public void maximizeFrame(Frame frame) {
	frame.setExtendedState(Frame.MAXIMIZED_BOTH);
}

public void iconifyFrame(Frame frame) {
	frame.setExtendedState(Frame.ICONIFIED);
}

public void restoreFrame(Frame frame) {
	frame.setExtendedState(Frame.NORMAL);
}

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

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

Leave a Comment

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

WordPress.com Logo

You are commenting using your WordPress.com 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