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