Create a simple centered window(JFrame). - Java Swing

Java examples for Swing:JFrame

Description

Create a simple centered window(JFrame).

Demo Code

/**/*w w w .  jav  a2 s  .c  o m*/
 * JFrameUtils
 * Created by Lu?s F. Loureiro, github.com/nczeroshift
 * Under MIT license
 */
//package com.java2s;
import javax.swing.*;

import java.awt.*;

public class Main {
    /**
     * Create a simple centered window(JFrame).
     * @param title Window title.
     * @param size Window size.
     * @param panel Window contents panel.
     * @param exitOnClose If true closes the application
     * @return New JFrame instance.
     */
    public static JFrame createCenteredWindow(String title, Dimension size,
            JPanel panel, boolean exitOnClose) {
        JFrame frame = new JFrame(title);
        frame.setSize(size);
        frame.setPreferredSize(size);

        if (exitOnClose)
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        else
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);

        return frame;
    }
}

Related Tutorials