1 package net.sf.openrocket.gui.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.Toolkit;
11 import java.awt.Window;
12 import java.awt.event.ActionEvent;
13 import java.awt.event.ActionListener;
14 import java.awt.event.ComponentAdapter;
15 import java.awt.event.ComponentEvent;
16 import java.awt.event.ComponentListener;
17 import java.awt.event.FocusListener;
18 import java.awt.event.KeyEvent;
19 import java.awt.event.MouseAdapter;
20 import java.awt.event.MouseEvent;
21 import java.awt.event.MouseListener;
22 import java.awt.event.WindowAdapter;
23 import java.awt.event.WindowEvent;
24 import java.beans.PropertyChangeListener;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.HashSet;
30 import java.util.List;
33 import javax.imageio.ImageIO;
34 import javax.swing.AbstractAction;
35 import javax.swing.AbstractButton;
36 import javax.swing.Action;
37 import javax.swing.BoundedRangeModel;
38 import javax.swing.ComboBoxModel;
39 import javax.swing.DefaultBoundedRangeModel;
40 import javax.swing.DefaultComboBoxModel;
41 import javax.swing.DefaultListSelectionModel;
42 import javax.swing.JButton;
43 import javax.swing.JComboBox;
44 import javax.swing.JComponent;
45 import javax.swing.JDialog;
46 import javax.swing.JFrame;
47 import javax.swing.JLabel;
48 import javax.swing.JRootPane;
49 import javax.swing.JSlider;
50 import javax.swing.JSpinner;
51 import javax.swing.JTable;
52 import javax.swing.JTree;
53 import javax.swing.KeyStroke;
54 import javax.swing.ListSelectionModel;
55 import javax.swing.LookAndFeel;
56 import javax.swing.RootPaneContainer;
57 import javax.swing.SpinnerModel;
58 import javax.swing.SpinnerNumberModel;
59 import javax.swing.SwingUtilities;
60 import javax.swing.UIManager;
61 import javax.swing.border.TitledBorder;
62 import javax.swing.event.ChangeListener;
63 import javax.swing.table.AbstractTableModel;
64 import javax.swing.table.DefaultTableColumnModel;
65 import javax.swing.table.DefaultTableModel;
66 import javax.swing.table.TableColumnModel;
67 import javax.swing.table.TableModel;
68 import javax.swing.tree.DefaultMutableTreeNode;
69 import javax.swing.tree.DefaultTreeModel;
70 import javax.swing.tree.DefaultTreeSelectionModel;
71 import javax.swing.tree.TreeModel;
72 import javax.swing.tree.TreeSelectionModel;
74 import net.sf.openrocket.gui.Resettable;
75 import net.sf.openrocket.logging.LogHelper;
76 import net.sf.openrocket.startup.Application;
77 import net.sf.openrocket.util.BugException;
78 import net.sf.openrocket.util.Invalidatable;
79 import net.sf.openrocket.util.MemoryManagement;
81 public class GUIUtil {
82 private static final LogHelper log = Application.getLogger();
84 private static final KeyStroke ESCAPE = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
85 private static final String CLOSE_ACTION_KEY = "escape:WINDOW_CLOSING";
87 private static final List<Image> images = new ArrayList<Image>();
89 loadImage("pix/icon/icon-256.png");
90 loadImage("pix/icon/icon-064.png");
91 loadImage("pix/icon/icon-048.png");
92 loadImage("pix/icon/icon-032.png");
93 loadImage("pix/icon/icon-016.png");
96 private static void loadImage(String file) {
99 is = ClassLoader.getSystemResourceAsStream(file);
104 Image image = ImageIO.read(is);
106 } catch (IOException ignore) {
107 ignore.printStackTrace();
112 * Return the DPI setting of the monitor. This is either the setting provided
113 * by the system or a user-specified DPI setting.
115 * @return the DPI setting to use.
117 public static double getDPI() {
118 int dpi = Application.getPreferences().getInt("DPI", 0); // Tenths of a dpi
121 dpi = Toolkit.getDefaultToolkit().getScreenResolution() * 10;
133 * Set suitable options for a single-use disposable dialog. This includes
134 * setting ESC to close the dialog, adding the appropriate window icons and
135 * setting the location based on the platform. If defaultButton is provided,
136 * it is set to the default button action.
138 * The default button must be already attached to the dialog.
140 * @param dialog the dialog.
141 * @param defaultButton the default button of the dialog, or <code>null</code>.
143 public static void setDisposableDialogOptions(JDialog dialog, JButton defaultButton) {
144 installEscapeCloseOperation(dialog);
145 setWindowIcons(dialog);
146 addModelNullingListener(dialog);
147 dialog.setLocationByPlatform(true);
148 dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
150 if (defaultButton != null) {
151 setDefaultButton(defaultButton);
158 * Add the correct action to close a JDialog when the ESC key is pressed.
159 * The dialog is closed by sending is a WINDOW_CLOSING event.
161 * @param dialog the dialog for which to install the action.
163 public static void installEscapeCloseOperation(final JDialog dialog) {
164 Action dispatchClosing = new AbstractAction() {
166 public void actionPerformed(ActionEvent event) {
167 log.user("Closing dialog " + dialog);
168 dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING));
171 JRootPane root = dialog.getRootPane();
172 root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ESCAPE, CLOSE_ACTION_KEY);
173 root.getActionMap().put(CLOSE_ACTION_KEY, dispatchClosing);
178 * Set the given button as the default button of the frame/dialog it is in. The button
179 * must be first attached to the window component hierarchy.
181 * @param button the button to set as the default button.
183 public static void setDefaultButton(JButton button) {
184 Window w = SwingUtilities.windowForComponent(button);
186 throw new IllegalArgumentException("Attach button to a window first.");
188 if (!(w instanceof RootPaneContainer)) {
189 throw new IllegalArgumentException("Button not attached to RootPaneContainer, w=" + w);
191 ((RootPaneContainer) w).getRootPane().setDefaultButton(button);
197 * Change the behavior of a component so that TAB and Shift-TAB cycles the focus of
198 * the components. This is necessary for e.g. <code>JTextArea</code>.
200 * @param c the component to modify
202 public static void setTabToFocusing(Component c) {
203 Set<KeyStroke> strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("pressed TAB")));
204 c.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, strokes);
205 strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("shift pressed TAB")));
206 c.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, strokes);
212 * Set the OpenRocket icons to the window icons.
214 * @param window the window to set.
216 public static void setWindowIcons(Window window) {
217 window.setIconImages(images);
221 * Add a listener to the provided window that will call {@link #setNullModels(Component)}
222 * on the window once it is closed. This method may only be used on single-use
223 * windows and dialogs, that will never be shown again once closed!
225 * @param window the window to add the listener to.
227 public static void addModelNullingListener(final Window window) {
228 window.addWindowListener(new WindowAdapter() {
230 public void windowClosed(WindowEvent e) {
231 log.debug("Clearing all models of window " + window);
232 setNullModels(window);
233 MemoryManagement.collectable(window);
241 * Set the best available look-and-feel into use.
243 public static void setBestLAF() {
245 * Set the look-and-feel. On Linux, Motif/Metal is sometimes incorrectly used
246 * which is butt-ugly, so if the system l&f is Motif/Metal, we search for a few
247 * other alternatives.
251 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
253 // Check whether we have an ugly L&F
254 LookAndFeel laf = UIManager.getLookAndFeel();
256 laf.getName().matches(".*[mM][oO][tT][iI][fF].*") ||
257 laf.getName().matches(".*[mM][eE][tT][aA][lL].*")) {
259 // Search for better LAF
260 UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
261 String lafNames[] = {
265 ".*[aA][qQ][uU][aA].*",
266 ".*[nN][iI][mM][bB].*"
269 lf: for (String lafName : lafNames) {
270 for (UIManager.LookAndFeelInfo l : info) {
271 if (l.getName().matches(lafName)) {
272 UIManager.setLookAndFeel(l.getClassName());
278 } catch (Exception e) {
279 log.warn("Error setting LAF: " + e);
285 * Changes the size of the font of the specified component by the given amount.
287 * @param component the component for which to change the font
288 * @param size the change in the font size
290 public static void changeFontSize(JComponent component, float size) {
291 Font font = component.getFont();
292 font = font.deriveFont(font.getSize2D() + size);
293 component.setFont(font);
299 * Automatically remember the size of a window. This stores the window size in the user
300 * preferences when resizing/maximizing the window and sets the state on the first call.
302 public static void rememberWindowSize(final Window window) {
303 window.addComponentListener(new ComponentAdapter() {
305 public void componentResized(ComponentEvent e) {
306 log.debug("Storing size of " + window.getClass().getName() + ": " + window.getSize());
307 ((SwingPreferences) Application.getPreferences()).setWindowSize(window.getClass(), window.getSize());
308 if (window instanceof JFrame) {
309 if ((((JFrame) window).getExtendedState() & JFrame.MAXIMIZED_BOTH) == JFrame.MAXIMIZED_BOTH) {
310 log.debug("Storing maximized state of " + window.getClass().getName());
311 ((SwingPreferences) Application.getPreferences()).setWindowMaximized(window.getClass());
317 if (((SwingPreferences) Application.getPreferences()).isWindowMaximized(window.getClass())) {
318 if (window instanceof JFrame) {
319 ((JFrame) window).setExtendedState(JFrame.MAXIMIZED_BOTH);
322 Dimension dim = ((SwingPreferences) Application.getPreferences()).getWindowSize(window.getClass());
331 * Automatically remember the position of a window. The position is stored in the user preferences
332 * every time the window is moved and set from there when first calling this method.
334 public static void rememberWindowPosition(final Window window) {
335 window.addComponentListener(new ComponentAdapter() {
337 public void componentMoved(ComponentEvent e) {
338 ((SwingPreferences) Application.getPreferences()).setWindowPosition(window.getClass(), window.getLocation());
342 // Set window position according to preferences, and set prefs when moving
343 Point position = ((SwingPreferences) Application.getPreferences()).getWindowPosition(window.getClass());
344 if (position != null) {
345 window.setLocationByPlatform(false);
346 window.setLocation(position);
352 * Changes the style of the font of the specified border.
354 * @param border the component for which to change the font
355 * @param style the change in the font style
357 public static void changeFontStyle(TitledBorder border, int style) {
359 * The fix of JRE bug #4129681 causes a TitledBorder occasionally to
360 * return a null font. We try to work around the issue by detecting it
361 * and reverting to the font of a JLabel instead.
363 Font font = border.getTitleFont();
365 log.error("Border font is null, reverting to JLabel font");
366 font = new JLabel().getFont();
368 log.error("JLabel font is null, not modifying font");
372 font = font.deriveFont(style);
374 throw new BugException("Derived font is null");
376 border.setTitleFont(font);
382 * Traverses recursively the component tree, and sets all applicable component
383 * models to null, so as to remove the listener connections. After calling this
384 * method the component hierarchy should no longed be used.
386 * All components that use custom models should be added to this method, as
387 * there exists no standard way of removing the model from a component.
389 * @param c the component (<code>null</code> is ok)
391 public static void setNullModels(Component c) {
395 // Remove various listeners
396 for (ComponentListener l : c.getComponentListeners()) {
397 c.removeComponentListener(l);
399 for (FocusListener l : c.getFocusListeners()) {
400 c.removeFocusListener(l);
402 for (MouseListener l : c.getMouseListeners()) {
403 c.removeMouseListener(l);
405 for (PropertyChangeListener l : c.getPropertyChangeListeners()) {
406 c.removePropertyChangeListener(l);
408 for (PropertyChangeListener l : c.getPropertyChangeListeners("model")) {
409 c.removePropertyChangeListener("model", l);
411 for (PropertyChangeListener l : c.getPropertyChangeListeners("action")) {
412 c.removePropertyChangeListener("action", l);
415 // Remove models for known components
416 // Why the FSCK must this be so hard?!?!?
418 if (c instanceof JSpinner) {
420 JSpinner spinner = (JSpinner) c;
421 for (ChangeListener l : spinner.getChangeListeners()) {
422 spinner.removeChangeListener(l);
424 SpinnerModel model = spinner.getModel();
425 spinner.setModel(new SpinnerNumberModel());
426 if (model instanceof Invalidatable) {
427 ((Invalidatable) model).invalidate();
430 } else if (c instanceof JSlider) {
432 JSlider slider = (JSlider) c;
433 for (ChangeListener l : slider.getChangeListeners()) {
434 slider.removeChangeListener(l);
436 BoundedRangeModel model = slider.getModel();
437 slider.setModel(new DefaultBoundedRangeModel());
438 if (model instanceof Invalidatable) {
439 ((Invalidatable) model).invalidate();
442 } else if (c instanceof JComboBox) {
444 JComboBox combo = (JComboBox) c;
445 for (ActionListener l : combo.getActionListeners()) {
446 combo.removeActionListener(l);
448 ComboBoxModel model = combo.getModel();
449 combo.setModel(new DefaultComboBoxModel());
450 if (model instanceof Invalidatable) {
451 ((Invalidatable) model).invalidate();
454 } else if (c instanceof AbstractButton) {
456 AbstractButton button = (AbstractButton) c;
457 for (ActionListener l : button.getActionListeners()) {
458 button.removeActionListener(l);
460 Action model = button.getAction();
461 button.setAction(new AbstractAction() {
463 public void actionPerformed(ActionEvent e) {
466 if (model instanceof Invalidatable) {
467 ((Invalidatable) model).invalidate();
470 } else if (c instanceof JTable) {
472 JTable table = (JTable) c;
473 TableModel model1 = table.getModel();
474 table.setModel(new DefaultTableModel());
475 if (model1 instanceof Invalidatable) {
476 ((Invalidatable) model1).invalidate();
479 TableColumnModel model2 = table.getColumnModel();
480 table.setColumnModel(new DefaultTableColumnModel());
481 if (model2 instanceof Invalidatable) {
482 ((Invalidatable) model2).invalidate();
485 ListSelectionModel model3 = table.getSelectionModel();
486 table.setSelectionModel(new DefaultListSelectionModel());
487 if (model3 instanceof Invalidatable) {
488 ((Invalidatable) model3).invalidate();
491 } else if (c instanceof JTree) {
493 JTree tree = (JTree) c;
494 TreeModel model1 = tree.getModel();
495 tree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
496 if (model1 instanceof Invalidatable) {
497 ((Invalidatable) model1).invalidate();
500 TreeSelectionModel model2 = tree.getSelectionModel();
501 tree.setSelectionModel(new DefaultTreeSelectionModel());
502 if (model2 instanceof Invalidatable) {
503 ((Invalidatable) model2).invalidate();
506 } else if (c instanceof Resettable) {
508 ((Resettable) c).resetModel();
512 // Recurse the component
513 if (c instanceof Container) {
514 Component[] cs = ((Container) c).getComponents();
515 for (Component sub : cs)
524 * A mouse listener that toggles the state of a boolean value in a table model
525 * when clicked on another column of the table.
527 * NOTE: If the table model does not extend AbstractTableModel, the model must
528 * fire a change event (which in normal table usage is not necessary).
530 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
532 public static class BooleanTableClickListener extends MouseAdapter {
534 private final JTable table;
535 private final int clickColumn;
536 private final int booleanColumn;
539 public BooleanTableClickListener(JTable table) {
544 public BooleanTableClickListener(JTable table, int clickColumn, int booleanColumn) {
546 this.clickColumn = clickColumn;
547 this.booleanColumn = booleanColumn;
551 public void mouseClicked(MouseEvent e) {
552 if (e.getButton() != MouseEvent.BUTTON1)
555 Point p = e.getPoint();
556 int col = table.columnAtPoint(p);
559 col = table.convertColumnIndexToModel(col);
560 if (col != clickColumn)
563 int row = table.rowAtPoint(p);
566 row = table.convertRowIndexToModel(row);
570 TableModel model = table.getModel();
571 Object value = model.getValueAt(row, booleanColumn);
573 if (!(value instanceof Boolean)) {
574 throw new IllegalStateException("Table value at row=" + row + " col=" +
575 booleanColumn + " is not a Boolean, value=" + value);
578 Boolean b = (Boolean) value;
580 model.setValueAt(b, row, booleanColumn);
581 if (model instanceof AbstractTableModel) {
582 ((AbstractTableModel) model).fireTableCellUpdated(row, booleanColumn);