Java examples for Swing:JFrame
pack Later
//package com.java2s; import java.awt.Component; import java.awt.Window; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.SwingUtilities; public class Main { public static void packLater(final Window win, final Component parent) { win.pack();//from www. ja v a 2 s. c o m win.setLocationRelativeTo(parent); win.addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { win.pack(); win.setLocationRelativeTo(parent); } }); } public static void addWindowListener(final Component source, final WindowListener listener) { if (source instanceof Window) { ((Window) source).addWindowListener(listener); } else { source.addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) == HierarchyEvent.SHOWING_CHANGED) { SwingUtilities.getWindowAncestor(source) .addWindowListener(listener); } } }); } } }