Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.monkeys.gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Point; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JPanel; import javax.swing.JWindow; import javax.swing.SwingUtilities; import org.apache.commons.lang.NullArgumentException; /** * popup window * * @author bowen */ public class PopupWindow extends JWindow { private JPanel panel; public PopupWindow(final Frame parent, final Component base) { super(parent); if (null == base) { throw new NullArgumentException("component"); } this.addWindowFocusListener(new WindowAdapter() { @Override public void windowLostFocus(WindowEvent e) { hidePopup(); } }); base.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { hidePopup(); } @Override public void componentMoved(ComponentEvent e) { hidePopup(); } @Override public void componentHidden(ComponentEvent e) { hidePopup(); } }); base.addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { hidePopup(); } }); } public PopupWindow(final Frame base) { super(base); } public void setPanel(final JPanel panel) { this.panel = panel; this.getContentPane().removeAll(); if (null == panel) { return; } Dimension size = panel.getPreferredSize(); if (null == size) { size = panel.getSize(); } if (size != null) { this.setSize(size); this.setPreferredSize(size); } final GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; this.setLayout(new GridBagLayout()); this.getContentPane().add(panel, c); } public void showPupup(final Component component) { this.showPupup(component, 0, component.getHeight() + 2); } public void showPupup(final Component component, final int relX, final int relY) { final Point xy = component.getLocationOnScreen(); if (relX != 0 || relY != 0) { xy.translate(relX, relY); } this.showPopup(xy.x, xy.y); } private void showPopup(final int x, final int y) { this.setLocation(x, y); this.setVisible(true); this.toFront(); this.requestFocusInWindow(); } public void hidePopup() { this.setVisible(false); } }