Java JFrame Center centerFrame(JFrame frame)

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

Description

Centers the frame on the screen and sets its bounds.

License

Open Source License

Parameter

Parameter Description
frame a parameter

Declaration

public static void centerFrame(JFrame frame) 

Method Source Code


//package com.java2s;
/*//from w  ww  .jav  a  2 s. co m
 * @(#)SwingUtils.java   2010.01.25 at 11:23:37 PST
 *
 * Copyright 2009 MBARI
 *
 *
 * 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.*;

import javax.swing.*;

public class Main {
    /**
     * Centers the frame on the screen and sets its bounds. THis method should be
     * used after you call frame.pack() or frame.setSize().
     * @param frame
     */
    public static void centerFrame(JFrame frame) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        Point center = ge.getCenterPoint();
        Rectangle bounds = ge.getMaximumWindowBounds();
        int w = Math.max(bounds.width / 2, Math.min(frame.getWidth(), bounds.width));
        int h = Math.max(bounds.height / 2, Math.min(frame.getHeight(), bounds.height));
        int x = center.x - w / 2, y = center.y - h / 2;
        frame.setBounds(x, y, w, h);

        if ((w == bounds.width) && (h == bounds.height)) {
            frame.setExtendedState(Frame.MAXIMIZED_BOTH);
        }

        frame.validate();
    }
}

Related

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