1 package net.sf.openrocket.util;
3 import java.awt.Component;
4 import java.awt.Container;
7 import java.awt.KeyboardFocusManager;
9 import java.awt.Window;
10 import java.awt.event.ActionEvent;
11 import java.awt.event.ActionListener;
12 import java.awt.event.ComponentListener;
13 import java.awt.event.FocusListener;
14 import java.awt.event.KeyEvent;
15 import java.awt.event.MouseAdapter;
16 import java.awt.event.MouseEvent;
17 import java.awt.event.MouseListener;
18 import java.awt.event.WindowAdapter;
19 import java.awt.event.WindowEvent;
20 import java.beans.PropertyChangeListener;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.HashSet;
26 import java.util.List;
29 import javax.imageio.ImageIO;
30 import javax.swing.AbstractAction;
31 import javax.swing.AbstractButton;
32 import javax.swing.Action;
33 import javax.swing.BoundedRangeModel;
34 import javax.swing.ComboBoxModel;
35 import javax.swing.DefaultBoundedRangeModel;
36 import javax.swing.DefaultComboBoxModel;
37 import javax.swing.DefaultListSelectionModel;
38 import javax.swing.JButton;
39 import javax.swing.JComboBox;
40 import javax.swing.JComponent;
41 import javax.swing.JDialog;
42 import javax.swing.JLabel;
43 import javax.swing.JRootPane;
44 import javax.swing.JSlider;
45 import javax.swing.JSpinner;
46 import javax.swing.JTable;
47 import javax.swing.JTree;
48 import javax.swing.KeyStroke;
49 import javax.swing.ListSelectionModel;
50 import javax.swing.LookAndFeel;
51 import javax.swing.RootPaneContainer;
52 import javax.swing.SpinnerModel;
53 import javax.swing.SpinnerNumberModel;
54 import javax.swing.SwingUtilities;
55 import javax.swing.UIManager;
56 import javax.swing.border.TitledBorder;
57 import javax.swing.event.ChangeListener;
58 import javax.swing.table.AbstractTableModel;
59 import javax.swing.table.DefaultTableColumnModel;
60 import javax.swing.table.DefaultTableModel;
61 import javax.swing.table.TableColumnModel;
62 import javax.swing.table.TableModel;
63 import javax.swing.tree.DefaultMutableTreeNode;
64 import javax.swing.tree.DefaultTreeModel;
65 import javax.swing.tree.DefaultTreeSelectionModel;
66 import javax.swing.tree.TreeModel;
67 import javax.swing.tree.TreeSelectionModel;
69 import net.sf.openrocket.gui.Resettable;
70 import net.sf.openrocket.logging.LogHelper;
71 import net.sf.openrocket.startup.Application;
73 public class GUIUtil {
74 private static final LogHelper log = Application.getLogger();
76 private static final KeyStroke ESCAPE = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
77 private static final String CLOSE_ACTION_KEY = "escape:WINDOW_CLOSING";
79 private static final List<Image> images = new ArrayList<Image>();
81 loadImage("pix/icon/icon-256.png");
82 loadImage("pix/icon/icon-064.png");
83 loadImage("pix/icon/icon-048.png");
84 loadImage("pix/icon/icon-032.png");
85 loadImage("pix/icon/icon-016.png");
88 private static void loadImage(String file) {
91 is = ClassLoader.getSystemResourceAsStream(file);
96 Image image = ImageIO.read(is);
98 } catch (IOException ignore) {
99 ignore.printStackTrace();
106 * Set suitable options for a single-use disposable dialog. This includes
107 * setting ESC to close the dialog, adding the appropriate window icons and
108 * setting the location based on the platform. If defaultButton is provided,
109 * it is set to the default button action.
111 * The default button must be already attached to the dialog.
113 * @param dialog the dialog.
114 * @param defaultButton the default button of the dialog, or <code>null</code>.
116 public static void setDisposableDialogOptions(JDialog dialog, JButton defaultButton) {
117 installEscapeCloseOperation(dialog);
118 setWindowIcons(dialog);
119 addModelNullingListener(dialog);
120 dialog.setLocationByPlatform(true);
121 dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
123 if (defaultButton != null) {
124 setDefaultButton(defaultButton);
131 * Add the correct action to close a JDialog when the ESC key is pressed.
132 * The dialog is closed by sending is a WINDOW_CLOSING event.
134 * @param dialog the dialog for which to install the action.
136 public static void installEscapeCloseOperation(final JDialog dialog) {
137 Action dispatchClosing = new AbstractAction() {
139 public void actionPerformed(ActionEvent event) {
140 log.user("Closing dialog " + dialog);
141 dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING));
144 JRootPane root = dialog.getRootPane();
145 root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ESCAPE, CLOSE_ACTION_KEY);
146 root.getActionMap().put(CLOSE_ACTION_KEY, dispatchClosing);
151 * Set the given button as the default button of the frame/dialog it is in. The button
152 * must be first attached to the window component hierarchy.
154 * @param button the button to set as the default button.
156 public static void setDefaultButton(JButton button) {
157 Window w = SwingUtilities.windowForComponent(button);
159 throw new IllegalArgumentException("Attach button to a window first.");
161 if (!(w instanceof RootPaneContainer)) {
162 throw new IllegalArgumentException("Button not attached to RootPaneContainer, w=" + w);
164 ((RootPaneContainer) w).getRootPane().setDefaultButton(button);
170 * Change the behavior of a component so that TAB and Shift-TAB cycles the focus of
171 * the components. This is necessary for e.g. <code>JTextArea</code>.
173 * @param c the component to modify
175 public static void setTabToFocusing(Component c) {
176 Set<KeyStroke> strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("pressed TAB")));
177 c.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, strokes);
178 strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("shift pressed TAB")));
179 c.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, strokes);
185 * Set the OpenRocket icons to the window icons.
187 * @param window the window to set.
189 public static void setWindowIcons(Window window) {
190 window.setIconImages(images);
194 * Add a listener to the provided window that will call {@link #setNullModels(Component)}
195 * on the window once it is closed. This method may only be used on single-use
196 * windows and dialogs, that will never be shown again once closed!
198 * @param window the window to add the listener to.
200 public static void addModelNullingListener(final Window window) {
201 window.addWindowListener(new WindowAdapter() {
203 public void windowClosed(WindowEvent e) {
204 log.debug("Clearing all models of window " + window);
205 setNullModels(window);
206 MemoryManagement.collectable(window);
214 * Set the best available look-and-feel into use.
216 public static void setBestLAF() {
218 * Set the look-and-feel. On Linux, Motif/Metal is sometimes incorrectly used
219 * which is butt-ugly, so if the system l&f is Motif/Metal, we search for a few
220 * other alternatives.
224 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
226 // Check whether we have an ugly L&F
227 LookAndFeel laf = UIManager.getLookAndFeel();
229 laf.getName().matches(".*[mM][oO][tT][iI][fF].*") ||
230 laf.getName().matches(".*[mM][eE][tT][aA][lL].*")) {
232 // Search for better LAF
233 UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels();
234 String lafNames[] = {
238 ".*[aA][qQ][uU][aA].*",
239 ".*[nN][iI][mM][bB].*"
242 lf: for (String lafName : lafNames) {
243 for (UIManager.LookAndFeelInfo l : info) {
244 if (l.getName().matches(lafName)) {
245 UIManager.setLookAndFeel(l.getClassName());
251 } catch (Exception e) {
252 log.warn("Error setting LAF: " + e);
258 * Changes the size of the font of the specified component by the given amount.
260 * @param component the component for which to change the font
261 * @param size the change in the font size
263 public static void changeFontSize(JComponent component, float size) {
264 Font font = component.getFont();
265 font = font.deriveFont(font.getSize2D() + size);
266 component.setFont(font);
271 * Changes the style of the font of the specified border.
273 * @param border the component for which to change the font
274 * @param style the change in the font style
276 public static void changeFontStyle(TitledBorder border, int style) {
278 * The fix of JRE bug #4129681 causes a TitledBorder occasionally to
279 * return a null font. We try to work around the issue by detecting it
280 * and reverting to the font of a JLabel instead.
282 Font font = border.getTitleFont();
284 log.error("Border font is null, reverting to JLabel font");
285 font = new JLabel().getFont();
287 log.error("JLabel font is null, not modifying font");
291 font = font.deriveFont(style);
293 throw new BugException("Derived font is null");
295 border.setTitleFont(font);
301 * Traverses recursively the component tree, and sets all applicable component
302 * models to null, so as to remove the listener connections. After calling this
303 * method the component hierarchy should no longed be used.
305 * All components that use custom models should be added to this method, as
306 * there exists no standard way of removing the model from a component.
308 * @param c the component (<code>null</code> is ok)
310 public static void setNullModels(Component c) {
314 // Remove various listeners
315 for (ComponentListener l : c.getComponentListeners()) {
316 c.removeComponentListener(l);
318 for (FocusListener l : c.getFocusListeners()) {
319 c.removeFocusListener(l);
321 for (MouseListener l : c.getMouseListeners()) {
322 c.removeMouseListener(l);
324 for (PropertyChangeListener l : c.getPropertyChangeListeners()) {
325 c.removePropertyChangeListener(l);
327 for (PropertyChangeListener l : c.getPropertyChangeListeners("model")) {
328 c.removePropertyChangeListener("model", l);
330 for (PropertyChangeListener l : c.getPropertyChangeListeners("action")) {
331 c.removePropertyChangeListener("action", l);
334 // Remove models for known components
335 // Why the FSCK must this be so hard?!?!?
337 if (c instanceof JSpinner) {
339 JSpinner spinner = (JSpinner) c;
340 for (ChangeListener l : spinner.getChangeListeners()) {
341 spinner.removeChangeListener(l);
343 SpinnerModel model = spinner.getModel();
344 spinner.setModel(new SpinnerNumberModel());
345 if (model instanceof Invalidatable) {
346 ((Invalidatable) model).invalidate();
349 } else if (c instanceof JSlider) {
351 JSlider slider = (JSlider) c;
352 for (ChangeListener l : slider.getChangeListeners()) {
353 slider.removeChangeListener(l);
355 BoundedRangeModel model = slider.getModel();
356 slider.setModel(new DefaultBoundedRangeModel());
357 if (model instanceof Invalidatable) {
358 ((Invalidatable) model).invalidate();
361 } else if (c instanceof JComboBox) {
363 JComboBox combo = (JComboBox) c;
364 for (ActionListener l : combo.getActionListeners()) {
365 combo.removeActionListener(l);
367 ComboBoxModel model = combo.getModel();
368 combo.setModel(new DefaultComboBoxModel());
369 if (model instanceof Invalidatable) {
370 ((Invalidatable) model).invalidate();
373 } else if (c instanceof AbstractButton) {
375 AbstractButton button = (AbstractButton) c;
376 for (ActionListener l : button.getActionListeners()) {
377 button.removeActionListener(l);
379 Action model = button.getAction();
380 button.setAction(new AbstractAction() {
382 public void actionPerformed(ActionEvent e) {
385 if (model instanceof Invalidatable) {
386 ((Invalidatable) model).invalidate();
389 } else if (c instanceof JTable) {
391 JTable table = (JTable) c;
392 TableModel model1 = table.getModel();
393 table.setModel(new DefaultTableModel());
394 if (model1 instanceof Invalidatable) {
395 ((Invalidatable) model1).invalidate();
398 TableColumnModel model2 = table.getColumnModel();
399 table.setColumnModel(new DefaultTableColumnModel());
400 if (model2 instanceof Invalidatable) {
401 ((Invalidatable) model2).invalidate();
404 ListSelectionModel model3 = table.getSelectionModel();
405 table.setSelectionModel(new DefaultListSelectionModel());
406 if (model3 instanceof Invalidatable) {
407 ((Invalidatable) model3).invalidate();
410 } else if (c instanceof JTree) {
412 JTree tree = (JTree) c;
413 TreeModel model1 = tree.getModel();
414 tree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
415 if (model1 instanceof Invalidatable) {
416 ((Invalidatable) model1).invalidate();
419 TreeSelectionModel model2 = tree.getSelectionModel();
420 tree.setSelectionModel(new DefaultTreeSelectionModel());
421 if (model2 instanceof Invalidatable) {
422 ((Invalidatable) model2).invalidate();
425 } else if (c instanceof Resettable) {
427 ((Resettable) c).resetModel();
431 // Recurse the component
432 if (c instanceof Container) {
433 Component[] cs = ((Container) c).getComponents();
434 for (Component sub : cs)
443 * A mouse listener that toggles the state of a boolean value in a table model
444 * when clicked on another column of the table.
446 * NOTE: If the table model does not extend AbstractTableModel, the model must
447 * fire a change event (which in normal table usage is not necessary).
449 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
451 public static class BooleanTableClickListener extends MouseAdapter {
453 private final JTable table;
454 private final int clickColumn;
455 private final int booleanColumn;
458 public BooleanTableClickListener(JTable table) {
463 public BooleanTableClickListener(JTable table, int clickColumn, int booleanColumn) {
465 this.clickColumn = clickColumn;
466 this.booleanColumn = booleanColumn;
470 public void mouseClicked(MouseEvent e) {
471 if (e.getButton() != MouseEvent.BUTTON1)
474 Point p = e.getPoint();
475 int col = table.columnAtPoint(p);
478 col = table.convertColumnIndexToModel(col);
479 if (col != clickColumn)
482 int row = table.rowAtPoint(p);
485 row = table.convertRowIndexToModel(row);
489 TableModel model = table.getModel();
490 Object value = model.getValueAt(row, booleanColumn);
492 if (!(value instanceof Boolean)) {
493 throw new IllegalStateException("Table value at row=" + row + " col=" +
494 booleanColumn + " is not a Boolean, value=" + value);
497 Boolean b = (Boolean) value;
499 model.setValueAt(b, row, booleanColumn);
500 if (model instanceof AbstractTableModel) {
501 ((AbstractTableModel) model).fireTableCellUpdated(row, booleanColumn);