Here you can find the source of setComponentLocationOnCenter(Component component)
Parameter | Description |
---|---|
component | the component to be moved to the center of the screen |
public static void setComponentLocationOnCenter(Component component)
//package com.java2s; /*//ww w . j a v a 2 s .co m * Copyright 2014 University of Aveiro * * 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. */ import java.awt.*; public class Main { /** * Centers the specified component based on the user main screen dimensions and resolution. * * @param component the component to be moved to the center of the screen */ public static void setComponentLocationOnCenter(Component component) { int screenID = getScreenID(component); Dimension dim = getScreenDimension(screenID); final int x = (dim.width - component.getWidth()) / 2; final int y = (dim.height - component.getHeight()) / 2; component.setLocation(x, y); } private static int getScreenID(Component component) { int scrID = 1; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gd = ge.getScreenDevices(); for (int i = 0; i < gd.length; i++) { GraphicsConfiguration gc = gd[i].getDefaultConfiguration(); Rectangle r = gc.getBounds(); if (r.contains(component.getLocation())) { scrID = i + 1; } } return scrID; } private static Dimension getScreenDimension(int scrID) { Dimension d = new Dimension(0, 0); if (scrID > 0) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); DisplayMode mode = ge.getScreenDevices()[scrID - 1].getDisplayMode(); d.setSize(mode.getWidth(), mode.getHeight()); } return d; } }