1 package net.sf.openrocket.util;
3 import java.awt.Component;
4 import java.awt.Container;
5 import java.awt.Dimension;
8 import java.awt.KeyboardFocusManager;
10 import java.awt.Window;
11 import java.awt.event.ActionEvent;
12 import java.awt.event.ActionListener;
13 import java.awt.event.ComponentAdapter;
14 import java.awt.event.ComponentEvent;
15 import java.awt.event.ComponentListener;
16 import java.awt.event.FocusListener;
17 import java.awt.event.KeyEvent;
18 import java.awt.event.MouseAdapter;
19 import java.awt.event.MouseEvent;
20 import java.awt.event.MouseListener;
21 import java.awt.event.WindowAdapter;
22 import java.awt.event.WindowEvent;
23 import java.beans.PropertyChangeListener;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.HashSet;
29 import java.util.List;
32 import javax.imageio.ImageIO;
33 import javax.swing.AbstractAction;
34 import javax.swing.AbstractButton;
35 import javax.swing.Action;
36 import javax.swing.BoundedRangeModel;
37 import javax.swing.ComboBoxModel;
38 import javax.swing.DefaultBoundedRangeModel;
39 import javax.swing.DefaultComboBoxModel;
40 import javax.swing.DefaultListSelectionModel;
41 import javax.swing.JButton;
42 import javax.swing.JComboBox;
43 import javax.swing.JComponent;
44 import javax.swing.JDialog;
45 import javax.swing.JFrame;
46 import javax.swing.JLabel;
47 import javax.swing.JRootPane;
48 import javax.swing.JSlider;
49 import javax.swing.JSpinner;
50 import javax.swing.JTable;
51 import javax.swing.JTree;
52 import javax.swing.KeyStroke;
53 import javax.swing.ListSelectionModel;
54 import javax.swing.LookAndFeel;
55 import javax.swing.RootPaneContainer;
56 import javax.swing.SpinnerModel;
57 import javax.swing.SpinnerNumberModel;
58 import javax.swing.SwingUtilities;
59 import javax.swing.UIManager;
60 import javax.swing.border.TitledBorder;
61 import javax.swing.event.ChangeListener;
62 import javax.swing.table.AbstractTableModel;
63 import javax.swing.table.DefaultTableColumnModel;
64 import javax.swing.table.DefaultTableModel;
65 import javax.swing.table.TableColumnModel;
66 import javax.swing.table.TableModel;
67 import javax.swing.tree.DefaultMutableTreeNode;
68 import javax.swing.tree.DefaultTreeModel;
69 import javax.swing.tree.DefaultTreeSelectionModel;
70 import javax.swing.tree.TreeModel;
71 import javax.swing.tree.TreeSelectionModel;
73 import net.sf.openrocket.gui.Resettable;
74 import net.sf.openrocket.logging.LogHelper;
75 import net.sf.openrocket.startup.Application;
77 public class GUIUtil {
78 private static final LogHelper log = Application.getLogger();
80 private static final KeyStroke ESCAPE = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
81 private static final String CLOSE_ACTION_KEY = "escape:WINDOW_CLOSING";
83 private static final List<Image> images = new ArrayList<Image>();
85 loadImage("pix/icon/icon-256.png");
86 loadImage("pix/icon/icon-064.png");
87 loadImage("pix/icon/icon-048.png");
88 loadImage("pix/icon/icon-032.png");
89 loadImage("pix/icon/icon-016.png");
92 private static void loadImage(String file) {
95 is = ClassLoader.getSystemResourceAsStream(file);
100 Image image = ImageIO.read(is);
102 } catch (IOException ignore) {
103 ignore.printStackTrace();
110 * Set suitable options for a single-use disposable dialog. This includes
111 * setting ESC to close the dialog, adding the appropriate window icons and
112 * setting the location based on the platform. If defaultButton is provided,
113 * it is set to the default button action.
115 * The default button must be already attached to the dialog.
117 * @param dialog the dialog.
118 * @param defaultButton the default button of the dialog, or <code>null</code>.
120 public static void setDisposableDialogOptions(JDialog dialog, JButton defaultButton) {
121 installEscapeCloseOperation(dialog);
122 setWindowIcons(dialog);
123 addModelNullingListener(dialog);
124 dialog.setLocationByPlatform(true);
125 dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
127 if (defaultButton != null) {
128 setDefaultButton(defaultButton);
135 * Add the correct action to close a JDialog when the ESC key is pressed.
136 * The dialog is closed by sending is a WINDOW_CLOSING event.
138 * @param dialog the dialog for which to install the action.
140 public static void installEscapeCloseOperation(final JDialog dialog) {
141 Action dispatchClosing = new AbstractAction() {
143 public void actionPerformed(ActionEvent event) {
144 log.user("Closing dialog " + dialog);
145 dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING));
148 JRootPane root = dialog.getRootPane();
149 root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ESCAPE, CLOSE_ACTION_KEY);
150 root.getActionMap().put(CLOSE_ACTION_KEY, dispatchClosing);
155 * Set the given button as the default button of the frame/dialog it is in. The button
156 * must be first attached to the window component hierarchy.
158 * @param button the button to set as the default button.
160 public static void setDefaultButton(JButton button) {
161 Window w = SwingUtilities.windowForComponent(button);
163 throw new IllegalArgumentException("Attach button to a window first.");
165 if (!(w instanceof RootPaneContainer)) {
166 throw new IllegalArgumentException("Button not attached to RootPaneContainer, w=" + w);
168 ((RootPaneContainer) w).getRootPane().setDefaultButton(button);
174 * Change the behavior of a component so that TAB and Shift-TAB cycles the focus of
175 * the components. This is necessary for e.g. <code>JTextArea</code>.
177 * @param c the component to modify
179 public static void setTabToFocusing(Component c) {
180 Set<KeyStroke> strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("pressed TAB")));
181 c.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, strokes);
182 strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("shift pressed TAB")));
183 c.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, strokes);
189 * Set the OpenRocket icons to the window icons.
191 * @param window the window to set.
193 public static void setWindowIcons(Window window) {
194 window.setIconImages(images);
198 * Add a listener to the provided window that will call {@link #setNullModels(Component)}
199 * on the window once it is closed. This method may only be used on single-use
200 * windows and dialogs, that will never be shown again once closed!
202 * @param window the window to add the listener to.
204 public static void addModelNullingListener(final Window window) {
205 window.addWindowListener(new WindowAdapter() {
207 public void windowClosed(WindowEvent e) {
208 log.debug("Clearing all models of window " + window);
209 setNullModels(window);
210 MemoryManagement.collectable(window);
218 * Set the best available look-and-feel into use.
220 public static void setBestLAF() {
222 * Set the look-and-feel. On Linux, Motif/Metal is sometimes incorrectly used
223 * which is butt-ugly, so if the system l&f is Motif/Metal, we search for a few
224 * other alternatives.
228 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
230 // Check whether we have an ugly L&F
231 LookAndFeel laf = UIManager.getLookAndFeel();
233 laf.getName().matches(".*[mM][oO][tT][iI][fF].*") ||
234 laf.getName().matches(".*[mM][eE][tT][aA][lL].*")) {
236 // Search for better LAF
237 UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
238 String lafNames[] = {
242 ".*[aA][qQ][uU][aA].*",
243 ".*[nN][iI][mM][bB].*"
246 lf: for (String lafName : lafNames) {
247 for (UIManager.LookAndFeelInfo l : info) {
248 if (l.getName().matches(lafName)) {
249 UIManager.setLookAndFeel(l.getClassName());
255 } catch (Exception e) {
256 log.warn("Error setting LAF: " + e);
262 * Changes the size of the font of the specified component by the given amount.
264 * @param component the component for which to change the font
265 * @param size the change in the font size
267 public static void changeFontSize(JComponent component, float size) {
268 Font font = component.getFont();
269 font = font.deriveFont(font.getSize2D() + size);
270 component.setFont(font);
276 * Automatically remember the size of a window. This stores the window size in the user
277 * preferences when resizing/maximizing the window and sets the state on the first call.
279 public static void rememberWindowSize(final Window window) {
280 window.addComponentListener(new ComponentAdapter() {
282 public void componentResized(ComponentEvent e) {
283 log.debug("Storing size of " + window.getClass().getName() + ": " + window.getSize());
284 Prefs.setWindowSize(window.getClass(), window.getSize());
285 if (window instanceof JFrame) {
286 if ((((JFrame) window).getExtendedState() & JFrame.MAXIMIZED_BOTH) == JFrame.MAXIMIZED_BOTH) {
287 log.debug("Storing maximized state of " + window.getClass().getName());
288 Prefs.setWindowMaximized(window.getClass());
294 if (Prefs.isWindowMaximized(window.getClass())) {
295 if (window instanceof JFrame) {
296 ((JFrame) window).setExtendedState(JFrame.MAXIMIZED_BOTH);
299 Dimension dim = Prefs.getWindowSize(window.getClass());
308 * Automatically remember the position of a window. The position is stored in the user preferences
309 * every time the window is moved and set from there when first calling this method.
311 public static void rememberWindowPosition(final Window window) {
312 window.addComponentListener(new ComponentAdapter() {
314 public void componentMoved(ComponentEvent e) {
315 Prefs.setWindowPosition(window.getClass(), window.getLocation());
319 // Set window position according to preferences, and set prefs when moving
320 Point position = Prefs.getWindowPosition(window.getClass());
321 if (position != null) {
322 window.setLocationByPlatform(false);
323 window.setLocation(position);
329 * Changes the style of the font of the specified border.
331 * @param border the component for which to change the font
332 * @param style the change in the font style
334 public static void changeFontStyle(TitledBorder border, int style) {
336 * The fix of JRE bug #4129681 causes a TitledBorder occasionally to
337 * return a null font. We try to work around the issue by detecting it
338 * and reverting to the font of a JLabel instead.
340 Font font = border.getTitleFont();
342 log.error("Border font is null, reverting to JLabel font");
343 font = new JLabel().getFont();
345 log.error("JLabel font is null, not modifying font");
349 font = font.deriveFont(style);
351 throw new BugException("Derived font is null");
353 border.setTitleFont(font);
359 * Traverses recursively the component tree, and sets all applicable component
360 * models to null, so as to remove the listener connections. After calling this
361 * method the component hierarchy should no longed be used.
363 * All components that use custom models should be added to this method, as
364 * there exists no standard way of removing the model from a component.
366 * @param c the component (<code>null</code> is ok)
368 public static void setNullModels(Component c) {
372 // Remove various listeners
373 for (ComponentListener l : c.getComponentListeners()) {
374 c.removeComponentListener(l);
376 for (FocusListener l : c.getFocusListeners()) {
377 c.removeFocusListener(l);
379 for (MouseListener l : c.getMouseListeners()) {
380 c.removeMouseListener(l);
382 for (PropertyChangeListener l : c.getPropertyChangeListeners()) {
383 c.removePropertyChangeListener(l);
385 for (PropertyChangeListener l : c.getPropertyChangeListeners("model")) {
386 c.removePropertyChangeListener("model", l);
388 for (PropertyChangeListener l : c.getPropertyChangeListeners("action")) {
389 c.removePropertyChangeListener("action", l);
392 // Remove models for known components
393 // Why the FSCK must this be so hard?!?!?
395 if (c instanceof JSpinner) {
397 JSpinner spinner = (JSpinner) c;
398 for (ChangeListener l : spinner.getChangeListeners()) {
399 spinner.removeChangeListener(l);
401 SpinnerModel model = spinner.getModel();
402 spinner.setModel(new SpinnerNumberModel());
403 if (model instanceof Invalidatable) {
404 ((Invalidatable) model).invalidate();
407 } else if (c instanceof JSlider) {
409 JSlider slider = (JSlider) c;
410 for (ChangeListener l : slider.getChangeListeners()) {
411 slider.removeChangeListener(l);
413 BoundedRangeModel model = slider.getModel();
414 slider.setModel(new DefaultBoundedRangeModel());
415 if (model instanceof Invalidatable) {
416 ((Invalidatable) model).invalidate();
419 } else if (c instanceof JComboBox) {
421 JComboBox combo = (JComboBox) c;
422 for (ActionListener l : combo.getActionListeners()) {
423 combo.removeActionListener(l);
425 ComboBoxModel model = combo.getModel();
426 combo.setModel(new DefaultComboBoxModel());
427 if (model instanceof Invalidatable) {
428 ((Invalidatable) model).invalidate();
431 } else if (c instanceof AbstractButton) {
433 AbstractButton button = (AbstractButton) c;
434 for (ActionListener l : button.getActionListeners()) {
435 button.removeActionListener(l);
437 Action model = button.getAction();
438 button.setAction(new AbstractAction() {
440 public void actionPerformed(ActionEvent e) {
443 if (model instanceof Invalidatable) {
444 ((Invalidatable) model).invalidate();
447 } else if (c instanceof JTable) {
449 JTable table = (JTable) c;
450 TableModel model1 = table.getModel();
451 table.setModel(new DefaultTableModel());
452 if (model1 instanceof Invalidatable) {
453 ((Invalidatable) model1).invalidate();
456 TableColumnModel model2 = table.getColumnModel();
457 table.setColumnModel(new DefaultTableColumnModel());
458 if (model2 instanceof Invalidatable) {
459 ((Invalidatable) model2).invalidate();
462 ListSelectionModel model3 = table.getSelectionModel();
463 table.setSelectionModel(new DefaultListSelectionModel());
464 if (model3 instanceof Invalidatable) {
465 ((Invalidatable) model3).invalidate();
468 } else if (c instanceof JTree) {
470 JTree tree = (JTree) c;
471 TreeModel model1 = tree.getModel();
472 tree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
473 if (model1 instanceof Invalidatable) {
474 ((Invalidatable) model1).invalidate();
477 TreeSelectionModel model2 = tree.getSelectionModel();
478 tree.setSelectionModel(new DefaultTreeSelectionModel());
479 if (model2 instanceof Invalidatable) {
480 ((Invalidatable) model2).invalidate();
483 } else if (c instanceof Resettable) {
485 ((Resettable) c).resetModel();
489 // Recurse the component
490 if (c instanceof Container) {
491 Component[] cs = ((Container) c).getComponents();
492 for (Component sub : cs)
501 * A mouse listener that toggles the state of a boolean value in a table model
502 * when clicked on another column of the table.
504 * NOTE: If the table model does not extend AbstractTableModel, the model must
505 * fire a change event (which in normal table usage is not necessary).
507 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
509 public static class BooleanTableClickListener extends MouseAdapter {
511 private final JTable table;
512 private final int clickColumn;
513 private final int booleanColumn;
516 public BooleanTableClickListener(JTable table) {
521 public BooleanTableClickListener(JTable table, int clickColumn, int booleanColumn) {
523 this.clickColumn = clickColumn;
524 this.booleanColumn = booleanColumn;
528 public void mouseClicked(MouseEvent e) {
529 if (e.getButton() != MouseEvent.BUTTON1)
532 Point p = e.getPoint();
533 int col = table.columnAtPoint(p);
536 col = table.convertColumnIndexToModel(col);
537 if (col != clickColumn)
540 int row = table.rowAtPoint(p);
543 row = table.convertRowIndexToModel(row);
547 TableModel model = table.getModel();
548 Object value = model.getValueAt(row, booleanColumn);
550 if (!(value instanceof Boolean)) {
551 throw new IllegalStateException("Table value at row=" + row + " col=" +
552 booleanColumn + " is not a Boolean, value=" + value);
555 Boolean b = (Boolean) value;
557 model.setValueAt(b, row, booleanColumn);
558 if (model instanceof AbstractTableModel) {
559 ((AbstractTableModel) model).fireTableCellUpdated(row, booleanColumn);