Java examples for Swing:JOptionPane
Adds a glass layer to the dialog to intercept all key events.
//package com.java2s; import java.awt.AWTEvent; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLayer; import javax.swing.Timer; import javax.swing.plaf.LayerUI; public class Main { /**//from w ww . j ava 2 s . c o m * Adds a glass layer to the dialog to intercept all key events. If the * espace key is pressed, the dialog is disposed (either with a fadeout * animation, or directly). */ public static void addEscapeToCloseSupport(final JDialog dialog, final boolean fadeOnClose) { LayerUI<Container> layerUI = new LayerUI<Container>() { private boolean closing = false; @Override public void installUI(JComponent c) { super.installUI(c); ((JLayer) c).setLayerEventMask(AWTEvent.KEY_EVENT_MASK); } @Override public void uninstallUI(JComponent c) { super.uninstallUI(c); ((JLayer) c).setLayerEventMask(0); } @Override public void eventDispatched(AWTEvent e, JLayer<? extends Container> l) { if (e instanceof KeyEvent && ((KeyEvent) e).getKeyCode() == KeyEvent.VK_ESCAPE) { if (closing) return; closing = true; if (fadeOnClose) fadeOut(dialog); else dialog.dispose(); } } }; JLayer<Container> layer = new JLayer<Container>( dialog.getContentPane(), layerUI); dialog.setContentPane(layer); } /** * Creates an animation to fade the dialog opacity from 1 to 0. */ public static void fadeOut(final JDialog dialog) { final Timer timer = new Timer(10, null); timer.setRepeats(true); timer.addActionListener(new ActionListener() { private float opacity = 1; @Override public void actionPerformed(ActionEvent e) { opacity -= 0.15f; dialog.setOpacity(Math.max(opacity, 0)); if (opacity <= 0) { timer.stop(); dialog.dispose(); } } }); dialog.setOpacity(1); timer.start(); } }