1 |
package skrueger.swing; |
2 |
|
3 |
import java.awt.Component; |
4 |
import java.awt.event.ActionEvent; |
5 |
import java.awt.event.ActionListener; |
6 |
import java.awt.event.KeyEvent; |
7 |
import java.awt.event.WindowAdapter; |
8 |
import java.awt.event.WindowEvent; |
9 |
|
10 |
import javax.swing.JComponent; |
11 |
import javax.swing.JDialog; |
12 |
import javax.swing.JRootPane; |
13 |
import javax.swing.KeyStroke; |
14 |
|
15 |
import schmitzm.swing.SwingUtil; |
16 |
|
17 |
public class AtlasDialog extends JDialog { |
18 |
|
19 |
public AtlasDialog(final Component owner, String title) { |
20 |
super(SwingUtil.getParentWindow(owner), title); |
21 |
initDialog(); |
22 |
} |
23 |
|
24 |
public AtlasDialog(final Component parentWindowComponent) { |
25 |
this(parentWindowComponent, null); |
26 |
} |
27 |
|
28 |
private void initDialog() { |
29 |
|
30 |
setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); |
31 |
|
32 |
addWindowListener(new WindowAdapter() { |
33 |
|
34 |
@Override |
35 |
public void windowClosing(WindowEvent e) { |
36 |
close(); |
37 |
} |
38 |
|
39 |
}); |
40 |
} |
41 |
|
42 |
/** |
43 |
* Allows to close the {@link JDialog} from "outside". {@link AtlasDialog} |
44 |
* is not implementing {@link Cancellable}, so the dialog is just disposed. |
45 |
*/ |
46 |
public boolean close() { |
47 |
dispose(); |
48 |
return true; |
49 |
} |
50 |
|
51 |
/** |
52 |
* Since the registerKeyboardAction() method is part of the JComponent class |
53 |
* definition, you must define the Escape keystroke and register the |
54 |
* keyboard action with a JComponent, not with a JDialog. The JRootPane for |
55 |
* the JDialog serves as an excellent choice to associate the registration, |
56 |
* as this will always be visible. If you override the protected |
57 |
* createRootPane() method of JDialog, you can return your custom JRootPane |
58 |
* with the keystroke enabled: |
59 |
*/ |
60 |
@Override |
61 |
protected JRootPane createRootPane() { |
62 |
final KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); |
63 |
final JRootPane rootPane = new JRootPane(); |
64 |
rootPane.registerKeyboardAction(new ActionListener() { |
65 |
|
66 |
public void actionPerformed(final ActionEvent e) { |
67 |
close(); |
68 |
} |
69 |
|
70 |
}, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); |
71 |
|
72 |
return rootPane; |
73 |
} |
74 |
} |