Thursday, October 4, 2012

How to display Window in the center of the screen

In Java, many of the swings applications by default opens the window at the top left corner of the screen. In addition to setting the size and making it visible, we also need to set the coordinates where the new window has to be displayed. To show the window in the center of the given screen/monitor, I have written an example explained below.

This example automatically takes the current screen resolution and depending on the size (of the window) provided, it adjusts the start point of the screen.

CenterOfScreen .java
package org.mbm.playground;

import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
import javax.swing.UIManager.LookAndFeelInfo;

public class CenterOfScreen extends JFrame {
    private static final long serialVersionUID = 1L;
    public CenterOfScreen() {
    private void init() {
        setTitle("Center Of Screen");
        // setLayout(new FlowLayout());
        // add(new JButton("JButton"));
        // add(new JTextField("JTextField"));
    private void setSizeWithPercentageOfScreenResolution(int percentage) {
        final double p = (double) percentage / 100;
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        setSize((int) (d.getWidth() * p), (int) (d.getHeight() * p));
    private void centerScreen(Dimension windowSize) {
        // get the default screen resolution.
        centerScreen(Toolkit.getDefaultToolkit().getScreenSize(), windowSize);
    private void centerScreen(Dimension screenResolution, Dimension windowSize) {
        // get center of the screen.
        int x = (int) (screenResolution.getWidth() / 2);
        int y = (int) (screenResolution.getHeight() / 2);
        // get the starting point for the window based on its size.
        x = (int) (x - (windowSize.getWidth() / 2));
        y = (int) (y - (windowSize.getHeight() / 2));
        // set the coordinates
        setLocation(x, y);
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
                    UnsupportedLookAndFeelException, InterruptedException { 
       CenterOfScreen f = new CenterOfScreen();       

There are two methods which does the tasks independently with each other. the first

this method takes the current screen resolution and calls setSize on current window with the given percentage.
This overloaded method takes the preferred dimensions of window and the screen resolution. Then after calculation sets the location by calling setLocation method. That is it, give a try!

No comments:

Post a Comment

Was this article useful?