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