center Window On Primary Screen - Android User Interface

Android examples for User Interface:Screen Position

Description

center Window On Primary Screen

Demo Code

/*******************************************************************************
 *    Copyright 2012 - Joakim Erdfelt//from w  ww  . ja  v  a  2s.  c o m
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 *******************************************************************************/
//package com.java2s;

import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;

import java.awt.Window;

public class Main {
    public static void centerWindowOnPrimaryScreen(Window win) {
        GraphicsEnvironment ge = GraphicsEnvironment
                .getLocalGraphicsEnvironment();
        GraphicsDevice[] gs = ge.getScreenDevices();

        Rectangle bounds = gs[0].getDefaultConfiguration().getBounds();
        Point screenCenter = new Point(bounds.width / 2, bounds.height / 2);
        Point winCenterRelative = new Point(win.getSize().width / 2,
                win.getSize().height / 2);
        win.setLocation((screenCenter.x - winCenterRelative.x),
                (screenCenter.y - winCenterRelative.y));
    }
}

Related Tutorials