package skrueger.swing; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JRootPane; import javax.swing.KeyStroke; import net.miginfocom.swing.MigLayout; import schmitzm.swing.SwingUtil; /** * A basic super class for atlas dialogs. It listens to the ESC key and calls * the {@link #close()} method. The layout manager is initialized with * {@link MigLayout}. */ public class AtlasDialog extends JDialog { public AtlasDialog(final Component owner, String title) { super(SwingUtil.getParentWindow(owner), title); initDialog(); } public AtlasDialog(final Component owner) { super(SwingUtil.getParentWindow(owner)); initDialog(); } /** A flag checking that we just get disposed once **/ protected boolean isDisposed = false; private void initDialog() { setLayout(new MigLayout("gap 1, inset 1")); setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { close(); } }); } /** * Allows to close the {@link JDialog} from "outside". {@link AtlasDialog} * is not implementing {@link Cancellable}, so the dialog is just disposed. */ public boolean close() { dispose(); return true; } /** * Since the registerKeyboardAction() method is part of the JComponent class * definition, you must define the Escape keystroke and register the * keyboard action with a JComponent, not with a JDialog. The JRootPane for * the JDialog serves as an excellent choice to associate the registration, * as this will always be visible. If you override the protected * createRootPane() method of JDialog, you can return your custom JRootPane * with the keystroke enabled: */ @Override protected JRootPane createRootPane() { final KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); final JRootPane rootPane = new JRootPane(); rootPane.registerKeyboardAction(new ActionListener() { public void actionPerformed(final ActionEvent e) { close(); } }, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); return rootPane; } @Override public void dispose() { super.dispose(); isDisposed = true; } }