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