Make your own free website on Tripod.com
Programmatically Center Frame in the Middle of the Screen

 

 


package tgk.aps.academic.ui;
 
import javax.swing.*;
import java.awt.*;
 
//import tgk.*;
 
/**
 *
 * @author  Tushar Kapila
 * Sample to center a frame in the middle of the screen, adjusting for the task bar.
 * To test run as :
 * javaw tgk/aps/academic/ui/ScreenCenter
 * then do not close change the first app ... resize the task bar and then start another instance of this app. 
 */
public class ScreenCenter  extends JPanel{
 
   public static void main(String[] args) {
        ScreenCenter ap = new ScreenCenter();
        ap.appMode(args);
    }
 
    void appMode(String[] args) {
 
        SwingUtilities.invokeLater(new Runnable() {
 
            public void run() {
 
                final JFrame frm = new JFrame("Sample Frame in Screen Center by sel2in.in ");
 
                Toolkit kit = frm.getToolkit();
                GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
                GraphicsDevice[] gs = ge.getScreenDevices();
                Insets in = kit.getScreenInsets(gs[0].getDefaultConfiguration());
 
                Dimension d = kit.getScreenSize();
                int max_width = (d.width - in.left - in.right);
                int max_height = (d.height - in.top - in.bottom);
                frm.setSize(Math.min(max_width, 850), Math.min(max_height, 550));//whatever size you want but smaller the insets
                frm.setLocation((int) (max_width - frm.getWidth()) / 2, (int) (max_height - frm.getHeight() ) / 2);
                Container pane = frm.getContentPane();
                //main gui is this app ... 
                pane.add(ScreenCenter.this);
                
                //frm.pack(); /// if you have implemented preferred size in your main gui
                frm.setVisible(true);
                frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
 
            }
        });
    }
    
}

////

On running you will see your frame in the screen center .