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 |
/** A flag checking that we just get disposed once **/ |
25 |
protected boolean isDisposed = false; |
26 |
|
27 |
|
28 |
public AtlasDialog(final Component parentWindowComponent) { |
29 |
this(parentWindowComponent, null); |
30 |
} |
31 |
|
32 |
private void initDialog() { |
33 |
|
34 |
setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); |
35 |
|
36 |
addWindowListener(new WindowAdapter() { |
37 |
|
38 |
@Override |
39 |
public void windowClosing(WindowEvent e) { |
40 |
close(); |
41 |
} |
42 |
|
43 |
}); |
44 |
} |
45 |
|
46 |
/** |
47 |
* Allows to close the {@link JDialog} from "outside". {@link AtlasDialog} |
48 |
* is not implementing {@link Cancellable}, so the dialog is just disposed. |
49 |
*/ |
50 |
public boolean close() { |
51 |
dispose(); |
52 |
return true; |
53 |
} |
54 |
|
55 |
/** |
56 |
* Since the registerKeyboardAction() method is part of the JComponent class |
57 |
* definition, you must define the Escape keystroke and register the |
58 |
* keyboard action with a JComponent, not with a JDialog. The JRootPane for |
59 |
* the JDialog serves as an excellent choice to associate the registration, |
60 |
* as this will always be visible. If you override the protected |
61 |
* createRootPane() method of JDialog, you can return your custom JRootPane |
62 |
* with the keystroke enabled: |
63 |
*/ |
64 |
@Override |
65 |
protected JRootPane createRootPane() { |
66 |
final KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); |
67 |
final JRootPane rootPane = new JRootPane(); |
68 |
rootPane.registerKeyboardAction(new ActionListener() { |
69 |
|
70 |
public void actionPerformed(final ActionEvent e) { |
71 |
close(); |
72 |
} |
73 |
|
74 |
}, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); |
75 |
|
76 |
return rootPane; |
77 |
} |
78 |
|
79 |
@Override |
80 |
public void dispose() { |
81 |
super.dispose(); |
82 |
isDisposed = true; |
83 |
} |
84 |
} |