create changelog entry
[debian/openrocket] / core / src / net / sf / openrocket / gui / main / MRUDesignFileAction.java
1 package net.sf.openrocket.gui.main;
2
3 import javax.swing.AbstractAction;
4 import javax.swing.Action;
5 import javax.swing.JMenu;
6 import javax.swing.JMenuItem;
7 import java.awt.Window;
8 import java.awt.event.ActionEvent;
9 import java.beans.PropertyChangeEvent;
10 import java.beans.PropertyChangeListener;
11 import java.io.File;
12 import java.util.List;
13
14 /**
15  * Implements a menu for the Most-Recently-Used Open Rocket design files.
16  */
17 public final class MRUDesignFileAction extends JMenu {
18
19     /**
20      * The window to which an open design file action will be parented to (typically an instance of BasicFrame).
21      */
22     private Window parent;
23
24     /**
25      * Constructor.
26      *
27      * @param s         the I18N menu string
28      * @param theParent the window to which an open design file action will be parented to (typically an instance of
29      *                  BasicFrame).
30      */
31     public MRUDesignFileAction(String s, Window theParent) {
32         super(s);
33
34         parent = theParent;
35         MRUDesignFile opts = MRUDesignFile.getInstance();
36         opts.addPropertyChangeListener(new PropertyChangeListener() {
37             public void propertyChange(PropertyChangeEvent evt) {
38                 if (!evt.getPropertyName().equals(MRUDesignFile.MRU_FILE_LIST_PROPERTY)) {
39                     return;
40                 }
41                 updateMenu();
42             }
43         });
44
45         updateMenu();
46     }
47
48     /**
49      * Create menu items.
50      */
51     private void updateMenu() {
52         removeAll();
53         List<String> list = MRUDesignFile.getInstance().getMRUFileList();
54         for (String name : list) {
55             Action action = createAction(name);
56             action.putValue(Action.NAME, name);
57             JMenuItem menuItem = new JMenuItem(action);
58             add(menuItem);
59         }
60     }
61
62     /**
63      * When a user clicks on one of the recently used design files, open it.
64      *
65      * @param file the design file name (absolute path)
66      *
67      * @return the action to open a design file
68      */
69     private Action createAction(String file) {
70         Action action = new AbstractAction() {
71             public void actionPerformed(ActionEvent e) {
72                 String command = e.getActionCommand();
73                 if (BasicFrame.open(new File(command), parent)) {
74                     MRUDesignFile.getInstance().addFile(command);
75                 }
76                 else {
77                     MRUDesignFile.getInstance().removeFile(command);
78                 }
79             }
80         };
81
82         action.putValue(Action.ACTION_COMMAND_KEY, file);
83         return action;
84     }
85
86 }