center Component inside its parent - Java Swing

Java examples for Swing:JPanel

Description

center Component inside its parent

Demo Code


//package com.java2s;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;

public class Main {
    public static void center(Component parent, Component c) {
        int w, h;
        if (parent != null) {
            w = parent.getWidth();/*www .ja va2 s. c om*/
            h = parent.getHeight();
        } else {
            Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
            w = size.width;
            h = size.height;
        }
        c.setLocation((w - c.getWidth()) / 2, (h - c.getHeight()) / 2);
    }
}

Related Tutorials