1 package net.sf.openrocket.util;
3 import java.awt.Component;
4 import java.awt.KeyboardFocusManager;
5 import java.awt.Window;
6 import java.awt.event.ActionEvent;
7 import java.awt.event.KeyEvent;
8 import java.awt.event.WindowEvent;
9 import java.util.Arrays;
10 import java.util.HashSet;
13 import javax.swing.AbstractAction;
14 import javax.swing.Action;
15 import javax.swing.JButton;
16 import javax.swing.JComponent;
17 import javax.swing.JDialog;
18 import javax.swing.JRootPane;
19 import javax.swing.KeyStroke;
20 import javax.swing.RootPaneContainer;
21 import javax.swing.SwingUtilities;
23 public class GUIUtil {
25 private static final KeyStroke ESCAPE = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
26 private static final String CLOSE_ACTION_KEY = "escape:WINDOW_CLOSING";
30 * Add the correct action to close a JDialog when the ESC key is pressed.
31 * The dialog is closed by sending is a WINDOW_CLOSING event.
33 * @param dialog the dialog for which to install the action.
35 public static void installEscapeCloseOperation(final JDialog dialog) {
36 Action dispatchClosing = new AbstractAction() {
37 public void actionPerformed(ActionEvent event) {
38 dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING));
41 JRootPane root = dialog.getRootPane();
42 root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ESCAPE, CLOSE_ACTION_KEY);
43 root.getActionMap().put(CLOSE_ACTION_KEY, dispatchClosing);
48 * Set the given button as the default button of the frame/dialog it is in. The button
49 * must be first attached to the window component hierarchy.
51 * @param button the button to set as the default button.
53 public static void setDefaultButton(JButton button) {
54 Window w = SwingUtilities.windowForComponent(button);
56 throw new IllegalArgumentException("Attach button to a window first.");
58 if (!(w instanceof RootPaneContainer)) {
59 throw new IllegalArgumentException("Button not attached to RootPaneContainer, w="+w);
61 ((RootPaneContainer)w).getRootPane().setDefaultButton(button);
67 * Change the behavior of a component so that TAB and Shift-TAB cycles the focus of
68 * the components. This is necessary for e.g. <code>JTextArea</code>.
70 * @param c the component to modify
72 public static void setTabToFocusing(Component c) {
73 Set<KeyStroke> strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("pressed TAB")));
74 c.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, strokes);
75 strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("shift pressed TAB")));
76 c.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, strokes);