Java JFrame Center centerFrame(JFrame frame)

Here you can find the source of centerFrame(JFrame frame)

Description

Centers a frame on the screen

License

Open Source License

Parameter

Parameter Description
frame the frame to center

Exception

Parameter Description
NullPointerException if frame is null

Declaration

public static void centerFrame(JFrame frame) throws NullPointerException 

Method Source Code


//package com.java2s;
/*/* w  ww .  j a v a 2  s. c o  m*/
 *                      ..::jDrawingLib::..
 *
 * Copyright (C) Federico Vera 2012 - 2014 <dktcoding [at] gmail>
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

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

import javax.swing.JFrame;

public class Main {
    /**
     * Centers a frame on the screen
     *
     * @param frame the frame to center
     * @throws NullPointerException if {@code frame} is {@code null}
     */
    public static void centerFrame(JFrame frame) throws NullPointerException {
        if (frame == null) {
            throw new NullPointerException("The frame can't be null");
        }

        final Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
        final Dimension f = frame.getSize();

        frame.setLocation((s.width - f.width) / 2, (s.height - f.height) / 2);
    }
}

Related

  1. centerDialog(JDialog dialog, JFrame parent)
  2. centerDialogIntoFrame(java.awt.Component p_CompToBePositioned, javax.swing.JFrame p_MainFrame)
  3. centerDialogOnFrame(JFrame parentFrame, JDialog dialog)
  4. centerFrame(final JFrame target)
  5. centerFrame(JFrame frame)
  6. centerFrame(JFrame frame)
  7. centerFrame(JFrame frame)
  8. centerFrame(JFrame frame)
  9. centerFrame(JFrame frame)