Wednesday, September 22, 2010

Centering a swing window on screen

In swing or AWT, if you initialize a frame or window by default its position start from the top left corner of screen. Some time it looks odd as we are intended to see the window/frame at center of screen.
To make a window centered, we all need to set the location of window to center with respect to screen size.
There are following steps to make a window centered.
1. Get the screen size
2. Set the window/frame location by calculating it with screen size and frame size.
See the following example.
centerOnScreen Method provide the functionality to make a window centered.


import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* @author ujjwal soni
*
*/
public class CenteredFrameExample {
JFrame frame;
JLabel label;
public CenteredFrameExample() {
frame = new JFrame("Centered JFrame.");
label = new JLabel();
frame.setSize(250, 150);
frame.setPreferredSize(new Dimension(250, 150));
frame.getContentPane().add(BorderLayout.CENTER, label);
centerOnScreen(frame);
frame.setVisible(true);
frame.pack();
}
public static void main(String args[]) {
CenteredFrameExample centeredFrame = new CenteredFrameExample();
String text = "This is the centered frame...
"; centeredFrame.label.setText(text); } /** * Centers a window on screen. * * @param w The window to center. */ public void centerOnScreen(Window w) { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); w.setLocation(screenSize.width / 2 - (w.getWidth() / 2), screenSize.height / 2 - (w.getHeight() / 2)); } }
 
Thats all for now....
Cheers!!!
Ujjwal Soni

No comments: